React Native

This guide will help you to quickly add the TalkJS inbox to your React Native app.

This guide assumes you already have a working React native application. If you don't, you can follow the official guide to quickly get started.

Library installation

We're going to use a WebView to display the TalkJS inbox in our application. WebView is not currently a part of the React Native core, so we need to install a library to use it:

npm install --save react-native-webview
# Or
yarn add react-native-webview

Adding the webview to the application

We're going to need the webview in our application, so let's add it (if you know what you're doing, you can add the webview anywhere you need it):

jsx
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
const baseUrl = 'https://talkjs.com'; // Set to your website, this is required for cookies to work properly
class MyInlineWeb extends Component {
render() {
return (
<WebView
source={{ baseUrl: baseUrl, html: '<h1>Hello world</h1>' }}
javaScriptEnabled={true}
domStorageEnabled={true}
sharedCookiesEnabled={true}
originWhitelist={['*']}
/>
);
}
}

Adding HTML contents

Now we need to ensure the TalkJS bundle is loaded in the webview so we can interact with it.

Let's add the HTML as a string to our application:

jsx
const html = `
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
(function(t,a,l,k,j,s){
s=a.createElement('script');s.async=1;s.src="https://cdn.talkjs.com/talk.js";a.head.appendChild(s)
;k=t.Promise;t.Talk={v:3,ready:{then:function(f){if(k)return new k(function(r,e){l.push([f,r,e])});l
.push([f])},catch:function(){return k&&new k()},c:l}};})(window,document,[]);
</script>
</head>
<body>
<div>
<div id="talkjs-container" style="width: 100%; height: 100%"><i>Loading chat...</i></div>
</div>
</body>
</html>
`
// And in component:
<WebView source={{ html: html }} /* other props */ />

Injecting JS to interact with TalkJS

We need to run additional code inside the WebView to set up the TalkJS inbox. For that we're going to inject some JavaScript. Webviews have multiple ways of injecting JS, and we're going to use injectedJavascript prop.

Important: WebView contents are rendered once at application startup, so if you update html contents of the source or the injectedJavascript you might not see the results until you reload the application. When you will need to run some TalkJS code in response to your user's actions when the WebView is already mounted, you can use the injectJavacript method of the WebView instance.

jsx
const injectedJavaScript = `
Talk.ready.then(() => {
// TalkJS code goes here
})
`
// And in component:
<WebView injectedJavaScript={injectedJavaScript} /* other props */ />

Setting up TalkJS

Now that we have our webview with TalkJS loadedd, let's set up actual TalkJS inbox and a conversation. All code here needs to run after the TalkJS is ready, so must be put inside the Talkjs.ready.then(() => { /* here */ }) block.

Get your appId

To get started, create an account or login to your dashboard to get your appId.

Create a TalkJS user

Now we'll create a TalkJS user. The Talk.User object is used to synchronize user data with TalkJS, so we can display it inside the chat UI.

For this guide, we will create a dummy TalkJS user to serve as the current user. Replace these values with the real data of your current user. In your injected script block, add the following:

javascript
Talk.ready.then(() => {
var me = new Talk.User({
id: '123456',
name: 'Alice',
photoUrl: 'https://demo.talkjs.com/img/alice.jpg',
welcomeMessage: 'Hey there! How are you? :-)',
role: 'default',
});
});

Create a TalkJS session

A session represents a user's active browser tab. It also authenticates your app with TalkJS. To create a session, you need your appId, which can be found on your dashboard, and the current TalkJS user we created previously.

javascript
window.talkSession = new Talk.Session({
appId: 'YOUR_APP_ID',
me: me,
});

Remember to replace YOUR_APP_ID with the appId found in the TalkJS dashboard. Better yet, log into the dashboard and navigate to the docs there and we'll have filled them out for you.

Create a conversation

A conversation happens between two or more people. So far we have just created one TalkJS user. Next, we'll create another user which we'll create a conversation with. For this example, we'll use a hardcoded dummy user.

javascript
var other = new Talk.User({
id: '654321',
name: 'Sebastian',
photoUrl: 'https://demo.talkjs.com/img/sebastian.jpg',
welcomeMessage: 'Hey, how can I help?',
role: 'default',
});

Next, we create a conversation. The getOrCreateConversation method attempts to get the conversation between the two users if it previously exists or create a new one otherwise. The Talk.oneOnOneId method predictably computes a Conversation ID based on participants' ids. Use this method if you want to simply create a conversation between two users. You may want to create a group conversation or generate a conversation ID associated with a transaction that happened on your platform e.g. a purchase. You can find how to do that here.

javascript
var conversation = talkSession.getOrCreateConversation(
Talk.oneOnOneId(me, other)
);

Next, we set the participants of the conversation to the users we created above.

javascript
conversation.setParticipant(me);
conversation.setParticipant(other);

A few more steps to go.

Create and mount the Inbox

The Inbox is one of the UI modes of TalkJS. It shows a user's conversation history and it allows them to write messages. You can find more UI modes here. To create the Inbox add this to your method.

javascript
var inbox = talkSession.createInbox({ selected: conversation });

You need to call the Inbox mount method after creating the Inbox to make it visible in your app. So add this line of code to your js file.

javascript
inbox.mount(document.getElementById('talkjs-container'));

In your body of your HTML file, add an element with the same ID that this will be mounted on.

html
<div>
<div
id="talkjs-container"
style="width: 100%; margin-top: 50px; height: 100%"
>
<i>Loading chat...</i>
</div>
</div>

Finally, to make the app responsive to the screen size, we add the following to the head of the HTML file, if it is not there already.

html
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

That's it, the inbox is all set now. The app should be working on you screen now. If it is not, reload the app - the WebView might have not picked up you code updates.

Go ahead, have a chat with Sebastian. He won't respond until a few steps from now but hey, it's a start! If you get an error, verify that appId is correct. Also you can take a look at WebView debugging docs to help you figure out the issue.

If you get stuck at any point, take a look at general mobile advice or reach out to us via our support chat.

We also have several examples for different use cases on our examples repository on GitHub.

Next, you can learn how to add notifications!