Skip to contentSkip to navigationSkip to topbar
On this page

Exploring the Conversations JavaScript Quickstart


What does the Conversations JavaScript Quickstart do? How does it work? How would you add something similar to your own project? We'll cover all of these questions and more in this behind-the-scenes look at the example application code.

If you haven't had a chance to try out the Conversations demo application, follow the instructions in the Twilio Conversations Quickstart guide to get it up and running.


Quickstart Overview

quickstart-overview page anchor

The example application code has two pieces - a large front-end Single Page Application (SPA) written with JavaScript and React, and a small back end written with JavaScript and Node.js. We created the project using the create-react-app(link takes you to an external page) command line tool.

Within the quickstart application, you will find examples of the following:

When you build an application that uses Conversations, you may be able to use several of the React components from the quickstart, or you may customize them to fit your use case. You also do not have to use React with Conversations - it works with vanilla JS, Angular(link takes you to an external page), Vue(link takes you to an external page), or any other JavaScript framework for the web browser.


Adding Twilio Conversations to your Application

adding-twilio-conversations-to-your-application page anchor

When you build your solutions with Twilio Conversations, you need a Conversations Client JavaScript SDK that runs in your end user's web browser. You can install this library using Node Package Manager (NPM), Yarn, or with an HTML Script tag that points to the Twilio CDN.

You also need to integrate a Twilio helper library into your back-end application. These libraries exist for Java, C#, PHP, Node.js/JavaScript, Ruby, and Python. You can use these libraries with almost any server framework that works with these languages.

Conversations JavaScript Client SDK

conversations-javascript-client-sdk page anchor

To install the JavaScript Conversations Client library in your web application's front end, use npm (or yarn):

npm install --save @twilio/conversations

There is also a CDN installation, if you prefer:

1
<script src="https://media.twiliocdn.com/sdk/js/conversations/releases/2.1.0/twilio-conversations.min.js"
2
integrity="sha256-v2SFLWujVq0wnwHpcxct7bzTP8wII7sumEhAKMEqgHQ="
3
crossorigin="anonymous"></script>
4

You would typically start by adding the Conversations.Client from this SDK to your project, and then work with Conversation objects to send and retrieve Message objects for a given Conversation. Other important classes are User, Participant, and Media.

While we cover some of the basics of the Conversations JS SDK in this Quickstart, you can find reference documentation for each class as JSDocs(link takes you to an external page). We also consider some of these topics in more detail on other pages in our docs, which we will link to in each section that has a corresponding guide.

These JavaScript libraries are not the libraries you need for a back-end, Node.js application. If you are building a web application with Node.js, you need the JavaScript Twilio Helper Library.

For your chosen language and/or platform, pick the appropriate Twilio Helper Library:

On each of these pages, you will find instructions for setting up the Twilio helper library (also called a "server-side SDK"). We recommend using dependency management for the Twilio libraries, and you'll find directions for the most common build tools for your platform.

(information)

Info

If you don't already have a Twilio account, sign up for a Twilio trial account(link takes you to an external page), and then create a new project. You'll also need to create an API Key and API Secret pair to call Twilio's REST API, whether you use one of the Twilio helper libraries, or make the API calls yourself.


Understanding Identity, Access Tokens, and Chat Grants

understanding-identity-access-tokens-and-chat-grants page anchor

Each chat user in your Conversations project needs an identity - this could be their user id, their username, or some kind of other identifier. You could certainly have anonymous users in your Conversations - for instance, a web chat popup with a customer service agent on an e-commerce website - but in that case, you would still want to issue some kind of identifier from your application.

Once you build Twilio Conversations into your project, you should generate an access token with a ChatGrant for end users, along with the identity value.

With the Conversations JS Quickstart, the easiest way to get started is to create an access token from the Twilio Command Line Interface (CLI).


Difference between Access Tokens, Auth Tokens and API Keys

difference-between-access-tokens-auth-tokens-and-api-keys page anchor

As part of this project, you will see that there are three different ways of providing credentials for Twilio - access tokens, auth tokens, and API keys. What is the difference between all of these different styles?

Access tokens provide short-lived credentials for a single end user to work with your Twilio service from a JavaScript application running in a web browser, or from a native iOS or Android mobile application. Use the Twilio helper libraries in your back-end web services to create access tokens for your front-end applications to consume. Alternatively, use the Twilio CLI to create access tokens for testing. These access tokens have a built-in expiration, and need to be refreshed from your server if your users have long-running connections. The Conversations client will update your application when access tokens are about to expire, or if they have expired, so that you can refresh the token.

Although the names are similar, authentication (or auth) tokens are not the same as access tokens, and cannot be used in the same way. The auth token pairs with your Twilio account identifier (also called the account SID) to provide authentication for the Twilio REST API. Your auth token should be treated with the same care that you would use to secure your Twilio password, and should never be included directly in source code, made available to a client application, or checked into a file in source control.

Similar to auth tokens, API key/secret pairs secure access to the Twilio REST API for your account. When you create an API key and secret pair from the Twilio console, the secret will only be shown once, and then it won't be recoverable. In your back-end application, you would authenticate to Twilio with a combination of your account identifier (also known as the "Account SID"), an API key, and an API secret.

The advantage of API keys over auth tokens is that you can rotate API keys on your server application, especially if you use one API key and secret pair for each application cluster or instance. This way, you can have multiple credentials under your Twilio account, and if you need to swap out a key pair and then deactivate it, you can do it on an application basis, not on an account basis.

Storing Credentials Securely

storing-credentials-securely page anchor

Whether you use auth tokens or API keys, we suggest that you store those credentials securely, and do not check them into source control. There are many different options for managing secure credentials that depend on how and where you run your development, staging, and production environments.

When you develop locally, look into using a .env file with your project, usually in conjunction with a library named dotenv. For .NET Core, read our article on Setting Twilio Environment Variables in Windows 10 with PowerShell and .NET Core 3.0(link takes you to an external page) to learn a lot more about this topic!


Retrieving a Conversations Access Token

retrieving-a-conversations-access-token page anchor

In the Conversations JS Quickstart, you can generate an access token using the Twilio Command Line Interface (CLI), and then paste that into the ConversationsApp.js file. While this works for getting the quickstart up and running, you will want to replace this with your own function that retrieves an access token.

You can use fetch, axios, or another client-side JS library to make an authenticated HTTP request to your server, where you would provide an access token with a ChatGrant that sets the identity for the user based on your own authentication mechanism (such as a session cookie).

Ideally, this method would be usable for three different scenarios:

  1. Initializing the Conversations JS Client when the React component mounts
  2. Refreshing the access token when the Conversations JS Client notifies your application that the token is about to expire
  3. Refreshing the access token when the Conversations JS Client notifies your application that the token did expire

Initializing the JS Conversations Client

initializing-the-js-conversations-client page anchor

The first step is to get an access token. Once you have an access token (It is a string value.), you can initialize a Twilio Conversations Client. This client is the central class in the Conversations JS SDK, and you need to keep it around after initialization. The client is designed to be long-lived, and it will fire events off that your project can subscribe to.

Initializing the Conversations Client

initializing-the-conversations-client page anchor
1
import React from "react";
2
import { Badge, Icon, Layout, Spin, Typography } from "antd";
3
import { Client as ConversationsClient } from "@twilio/conversations";
4
5
import "./assets/Conversation.css";
6
import "./assets/ConversationSection.css";
7
import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";
8
9
import Conversation from "./Conversation";
10
import LoginPage from "./LoginPage";
11
import { ConversationsList } from "./ConversationsList";
12
import { HeaderItem } from "./HeaderItem";
13
14
const { Content, Sider, Header } = Layout;
15
const { Text } = Typography;
16
17
class ConversationsApp extends React.Component {
18
constructor(props) {
19
super(props);
20
21
const name = localStorage.getItem("name") || "";
22
const loggedIn = name !== "";
23
24
this.state = {
25
name,
26
loggedIn,
27
token: null,
28
statusString: null,
29
conversationsReady: false,
30
conversations: [],
31
selectedConversationSid: null,
32
newMessage: ""
33
};
34
}
35
36
componentDidMount = () => {
37
if (this.state.loggedIn) {
38
this.getToken();
39
this.setState({ statusString: "Fetching credentials…" });
40
}
41
};
42
43
logIn = (name) => {
44
if (name !== "") {
45
localStorage.setItem("name", name);
46
this.setState({ name, loggedIn: true }, this.getToken);
47
}
48
};
49
50
logOut = (event) => {
51
if (event) {
52
event.preventDefault();
53
}
54
55
this.setState({
56
name: "",
57
loggedIn: false,
58
token: "",
59
conversationsReady: false,
60
messages: [],
61
newMessage: "",
62
conversations: []
63
});
64
65
localStorage.removeItem("name");
66
this.conversationsClient.shutdown();
67
};
68
69
getToken = () => {
70
// Paste your unique Chat token function
71
const myToken = "<Your token here>";
72
this.setState({ token: myToken }, this.initConversations);
73
};
74
75
initConversations = async () => {
76
window.conversationsClient = ConversationsClient;
77
this.conversationsClient = new ConversationsClient(this.state.token);
78
this.setState({ statusString: "Connecting to Twilio…" });
79
80
this.conversationsClient.on("connectionStateChanged", (state) => {
81
if (state === "connecting")
82
this.setState({
83
statusString: "Connecting to Twilio…",
84
status: "default"
85
});
86
if (state === "connected") {
87
this.setState({
88
statusString: "You are connected.",
89
status: "success"
90
});
91
}
92
if (state === "disconnecting")
93
this.setState({
94
statusString: "Disconnecting from Twilio…",
95
conversationsReady: false,
96
status: "default"
97
});
98
if (state === "disconnected")
99
this.setState({
100
statusString: "Disconnected.",
101
conversationsReady: false,
102
status: "warning"
103
});
104
if (state === "denied")
105
this.setState({
106
statusString: "Failed to connect.",
107
conversationsReady: false,
108
status: "error"
109
});
110
});
111
this.conversationsClient.on("conversationJoined", (conversation) => {
112
this.setState({ conversations: [...this.state.conversations, conversation] });
113
});
114
this.conversationsClient.on("conversationLeft", (thisConversation) => {
115
this.setState({
116
conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]
117
});
118
});
119
};
120
121
render() {
122
const { conversations, selectedConversationSid, status } = this.state;
123
const selectedConversation = conversations.find(
124
(it) => it.sid === selectedConversationSid
125
);
126
127
let conversationContent;
128
if (selectedConversation) {
129
conversationContent = (
130
<Conversation
131
conversationProxy={selectedConversation}
132
myIdentity={this.state.name}
133
/>
134
);
135
} else if (status !== "success") {
136
conversationContent = "Loading your conversation!";
137
} else {
138
conversationContent = "";
139
}
140
141
if (this.state.loggedIn) {
142
return (
143
<div className="conversations-window-wrapper">
144
<Layout className="conversations-window-container">
145
<Header
146
style={{ display: "flex", alignItems: "center", padding: 0 }}
147
>
148
<div
149
style={{
150
maxWidth: "250px",
151
width: "100%",
152
display: "flex",
153
alignItems: "center"
154
}}
155
>
156
<HeaderItem style={{ paddingRight: "0", display: "flex" }}>
157
<Logo />
158
</HeaderItem>
159
<HeaderItem>
160
<Text strong style={{ color: "white" }}>
161
Conversations
162
</Text>
163
</HeaderItem>
164
</div>
165
<div style={{ display: "flex", width: "100%" }}>
166
<HeaderItem>
167
<Text strong style={{ color: "white" }}>
168
{selectedConversation &&
169
(selectedConversation.friendlyName || selectedConversation.sid)}
170
</Text>
171
</HeaderItem>
172
<HeaderItem style={{ float: "right", marginLeft: "auto" }}>
173
<span
174
style={{ color: "white" }}
175
>{` ${this.state.statusString}`}</span>
176
<Badge
177
dot={true}
178
status={this.state.status}
179
style={{ marginLeft: "1em" }}
180
/>
181
</HeaderItem>
182
<HeaderItem>
183
<Icon
184
type="poweroff"
185
onClick={this.logOut}
186
style={{
187
color: "white",
188
fontSize: "20px",
189
marginLeft: "auto"
190
}}
191
/>
192
</HeaderItem>
193
</div>
194
</Header>
195
<Layout>
196
<Sider theme={"light"} width={250}>
197
<ConversationsList
198
conversations={conversations}
199
selectedConversationSid={selectedConversationSid}
200
onConversationClick={(item) => {
201
this.setState({ selectedConversationSid: item.sid });
202
}}
203
/>
204
</Sider>
205
<Content className="conversation-section">
206
<div id="SelectedConversation">{conversationContent}</div>
207
</Content>
208
</Layout>
209
</Layout>
210
</div>
211
);
212
}
213
214
return <LoginPage onSubmit={this.logIn} />;
215
}
216
}
217
218
export default ConversationsApp;

After you initialize the Conversations client, the connectionStateChanged event will fire any time the user's connection changes. The possible states handled in the Conversations JS Quickstart are:

  • connecting
  • connected
  • disconnecting
  • disconnected
  • denied

Once the user is connected, they are able to chat with others in conversations.

Managing the Connection State

managing-the-connection-state page anchor
1
import React from "react";
2
import { Badge, Icon, Layout, Spin, Typography } from "antd";
3
import { Client as ConversationsClient } from "@twilio/conversations";
4
5
import "./assets/Conversation.css";
6
import "./assets/ConversationSection.css";
7
import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";
8
9
import Conversation from "./Conversation";
10
import LoginPage from "./LoginPage";
11
import { ConversationsList } from "./ConversationsList";
12
import { HeaderItem } from "./HeaderItem";
13
14
const { Content, Sider, Header } = Layout;
15
const { Text } = Typography;
16
17
class ConversationsApp extends React.Component {
18
constructor(props) {
19
super(props);
20
21
const name = localStorage.getItem("name") || "";
22
const loggedIn = name !== "";
23
24
this.state = {
25
name,
26
loggedIn,
27
token: null,
28
statusString: null,
29
conversationsReady: false,
30
conversations: [],
31
selectedConversationSid: null,
32
newMessage: ""
33
};
34
}
35
36
componentDidMount = () => {
37
if (this.state.loggedIn) {
38
this.getToken();
39
this.setState({ statusString: "Fetching credentials…" });
40
}
41
};
42
43
logIn = (name) => {
44
if (name !== "") {
45
localStorage.setItem("name", name);
46
this.setState({ name, loggedIn: true }, this.getToken);
47
}
48
};
49
50
logOut = (event) => {
51
if (event) {
52
event.preventDefault();
53
}
54
55
this.setState({
56
name: "",
57
loggedIn: false,
58
token: "",
59
conversationsReady: false,
60
messages: [],
61
newMessage: "",
62
conversations: []
63
});
64
65
localStorage.removeItem("name");
66
this.conversationsClient.shutdown();
67
};
68
69
getToken = () => {
70
// Paste your unique Chat token function
71
const myToken = "<Your token here>";
72
this.setState({ token: myToken }, this.initConversations);
73
};
74
75
initConversations = async () => {
76
window.conversationsClient = ConversationsClient;
77
this.conversationsClient = new ConversationsClient(this.state.token);
78
this.setState({ statusString: "Connecting to Twilio…" });
79
80
this.conversationsClient.on("connectionStateChanged", (state) => {
81
if (state === "connecting")
82
this.setState({
83
statusString: "Connecting to Twilio…",
84
status: "default"
85
});
86
if (state === "connected") {
87
this.setState({
88
statusString: "You are connected.",
89
status: "success"
90
});
91
}
92
if (state === "disconnecting")
93
this.setState({
94
statusString: "Disconnecting from Twilio…",
95
conversationsReady: false,
96
status: "default"
97
});
98
if (state === "disconnected")
99
this.setState({
100
statusString: "Disconnected.",
101
conversationsReady: false,
102
status: "warning"
103
});
104
if (state === "denied")
105
this.setState({
106
statusString: "Failed to connect.",
107
conversationsReady: false,
108
status: "error"
109
});
110
});
111
this.conversationsClient.on("conversationJoined", (conversation) => {
112
this.setState({ conversations: [...this.state.conversations, conversation] });
113
});
114
this.conversationsClient.on("conversationLeft", (thisConversation) => {
115
this.setState({
116
conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]
117
});
118
});
119
};
120
121
render() {
122
const { conversations, selectedConversationSid, status } = this.state;
123
const selectedConversation = conversations.find(
124
(it) => it.sid === selectedConversationSid
125
);
126
127
let conversationContent;
128
if (selectedConversation) {
129
conversationContent = (
130
<Conversation
131
conversationProxy={selectedConversation}
132
myIdentity={this.state.name}
133
/>
134
);
135
} else if (status !== "success") {
136
conversationContent = "Loading your conversation!";
137
} else {
138
conversationContent = "";
139
}
140
141
if (this.state.loggedIn) {
142
return (
143
<div className="conversations-window-wrapper">
144
<Layout className="conversations-window-container">
145
<Header
146
style={{ display: "flex", alignItems: "center", padding: 0 }}
147
>
148
<div
149
style={{
150
maxWidth: "250px",
151
width: "100%",
152
display: "flex",
153
alignItems: "center"
154
}}
155
>
156
<HeaderItem style={{ paddingRight: "0", display: "flex" }}>
157
<Logo />
158
</HeaderItem>
159
<HeaderItem>
160
<Text strong style={{ color: "white" }}>
161
Conversations
162
</Text>
163
</HeaderItem>
164
</div>
165
<div style={{ display: "flex", width: "100%" }}>
166
<HeaderItem>
167
<Text strong style={{ color: "white" }}>
168
{selectedConversation &&
169
(selectedConversation.friendlyName || selectedConversation.sid)}
170
</Text>
171
</HeaderItem>
172
<HeaderItem style={{ float: "right", marginLeft: "auto" }}>
173
<span
174
style={{ color: "white" }}
175
>{` ${this.state.statusString}`}</span>
176
<Badge
177
dot={true}
178
status={this.state.status}
179
style={{ marginLeft: "1em" }}
180
/>
181
</HeaderItem>
182
<HeaderItem>
183
<Icon
184
type="poweroff"
185
onClick={this.logOut}
186
style={{
187
color: "white",
188
fontSize: "20px",
189
marginLeft: "auto"
190
}}
191
/>
192
</HeaderItem>
193
</div>
194
</Header>
195
<Layout>
196
<Sider theme={"light"} width={250}>
197
<ConversationsList
198
conversations={conversations}
199
selectedConversationSid={selectedConversationSid}
200
onConversationClick={(item) => {
201
this.setState({ selectedConversationSid: item.sid });
202
}}
203
/>
204
</Sider>
205
<Content className="conversation-section">
206
<div id="SelectedConversation">{conversationContent}</div>
207
</Content>
208
</Layout>
209
</Layout>
210
</div>
211
);
212
}
213
214
return <LoginPage onSubmit={this.logIn} />;
215
}
216
}
217
218
export default ConversationsApp;

Joining and Leaving a Conversation

joining-and-leaving-a-conversation page anchor

The Conversation class is the building block of your Conversations application. In the JS Quickstart, as the user joins or leaves conversations, conversationJoined and conversationLeft events from the ConversationsClient get fired with the Conversation object as an argument. The React application maintains the list of conversations in its state, and then displays those conversations to the user in the ConversationsList.js(link takes you to an external page) component.

Joining and Leaving Conversations

joining-and-leaving-conversations page anchor
1
import React from "react";
2
import { Badge, Icon, Layout, Spin, Typography } from "antd";
3
import { Client as ConversationsClient } from "@twilio/conversations";
4
5
import "./assets/Conversation.css";
6
import "./assets/ConversationSection.css";
7
import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";
8
9
import Conversation from "./Conversation";
10
import LoginPage from "./LoginPage";
11
import { ConversationsList } from "./ConversationsList";
12
import { HeaderItem } from "./HeaderItem";
13
14
const { Content, Sider, Header } = Layout;
15
const { Text } = Typography;
16
17
class ConversationsApp extends React.Component {
18
constructor(props) {
19
super(props);
20
21
const name = localStorage.getItem("name") || "";
22
const loggedIn = name !== "";
23
24
this.state = {
25
name,
26
loggedIn,
27
token: null,
28
statusString: null,
29
conversationsReady: false,
30
conversations: [],
31
selectedConversationSid: null,
32
newMessage: ""
33
};
34
}
35
36
componentDidMount = () => {
37
if (this.state.loggedIn) {
38
this.getToken();
39
this.setState({ statusString: "Fetching credentials…" });
40
}
41
};
42
43
logIn = (name) => {
44
if (name !== "") {
45
localStorage.setItem("name", name);
46
this.setState({ name, loggedIn: true }, this.getToken);
47
}
48
};
49
50
logOut = (event) => {
51
if (event) {
52
event.preventDefault();
53
}
54
55
this.setState({
56
name: "",
57
loggedIn: false,
58
token: "",
59
conversationsReady: false,
60
messages: [],
61
newMessage: "",
62
conversations: []
63
});
64
65
localStorage.removeItem("name");
66
this.conversationsClient.shutdown();
67
};
68
69
getToken = () => {
70
// Paste your unique Chat token function
71
const myToken = "<Your token here>";
72
this.setState({ token: myToken }, this.initConversations);
73
};
74
75
initConversations = async () => {
76
window.conversationsClient = ConversationsClient;
77
this.conversationsClient = new ConversationsClient(this.state.token);
78
this.setState({ statusString: "Connecting to Twilio…" });
79
80
this.conversationsClient.on("connectionStateChanged", (state) => {
81
if (state === "connecting")
82
this.setState({
83
statusString: "Connecting to Twilio…",
84
status: "default"
85
});
86
if (state === "connected") {
87
this.setState({
88
statusString: "You are connected.",
89
status: "success"
90
});
91
}
92
if (state === "disconnecting")
93
this.setState({
94
statusString: "Disconnecting from Twilio…",
95
conversationsReady: false,
96
status: "default"
97
});
98
if (state === "disconnected")
99
this.setState({
100
statusString: "Disconnected.",
101
conversationsReady: false,
102
status: "warning"
103
});
104
if (state === "denied")
105
this.setState({
106
statusString: "Failed to connect.",
107
conversationsReady: false,
108
status: "error"
109
});
110
});
111
this.conversationsClient.on("conversationJoined", (conversation) => {
112
this.setState({ conversations: [...this.state.conversations, conversation] });
113
});
114
this.conversationsClient.on("conversationLeft", (thisConversation) => {
115
this.setState({
116
conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]
117
});
118
});
119
};
120
121
render() {
122
const { conversations, selectedConversationSid, status } = this.state;
123
const selectedConversation = conversations.find(
124
(it) => it.sid === selectedConversationSid
125
);
126
127
let conversationContent;
128
if (selectedConversation) {
129
conversationContent = (
130
<Conversation
131
conversationProxy={selectedConversation}
132
myIdentity={this.state.name}
133
/>
134
);
135
} else if (status !== "success") {
136
conversationContent = "Loading your conversation!";
137
} else {
138
conversationContent = "";
139
}
140
141
if (this.state.loggedIn) {
142
return (
143
<div className="conversations-window-wrapper">
144
<Layout className="conversations-window-container">
145
<Header
146
style={{ display: "flex", alignItems: "center", padding: 0 }}
147
>
148
<div
149
style={{
150
maxWidth: "250px",
151
width: "100%",
152
display: "flex",
153
alignItems: "center"
154
}}
155
>
156
<HeaderItem style={{ paddingRight: "0", display: "flex" }}>
157
<Logo />
158
</HeaderItem>
159
<HeaderItem>
160
<Text strong style={{ color: "white" }}>
161
Conversations
162
</Text>
163
</HeaderItem>
164
</div>
165
<div style={{ display: "flex", width: "100%" }}>
166
<HeaderItem>
167
<Text strong style={{ color: "white" }}>
168
{selectedConversation &&
169
(selectedConversation.friendlyName || selectedConversation.sid)}
170
</Text>
171
</HeaderItem>
172
<HeaderItem style={{ float: "right", marginLeft: "auto" }}>
173
<span
174
style={{ color: "white" }}
175
>{` ${this.state.statusString}`}</span>
176
<Badge
177
dot={true}
178
status={this.state.status}
179
style={{ marginLeft: "1em" }}
180
/>
181
</HeaderItem>
182
<HeaderItem>
183
<Icon
184
type="poweroff"
185
onClick={this.logOut}
186
style={{
187
color: "white",
188
fontSize: "20px",
189
marginLeft: "auto"
190
}}
191
/>
192
</HeaderItem>
193
</div>
194
</Header>
195
<Layout>
196
<Sider theme={"light"} width={250}>
197
<ConversationsList
198
conversations={conversations}
199
selectedConversationSid={selectedConversationSid}
200
onConversationClick={(item) => {
201
this.setState({ selectedConversationSid: item.sid });
202
}}
203
/>
204
</Sider>
205
<Content className="conversation-section">
206
<div id="SelectedConversation">{conversationContent}</div>
207
</Content>
208
</Layout>
209
</Layout>
210
</div>
211
);
212
}
213
214
return <LoginPage onSubmit={this.logIn} />;
215
}
216
}
217
218
export default ConversationsApp;

Sending Messages to a Conversation

sending-messages-to-a-conversation page anchor

To send a message (with text content) to a conversation that a user has joined, you need to call the sendMessage() method on the Conversation instance. In the quickstart, we update the React component's state for the newMessage variable to be empty, leaving the text input field open for another message.

While the Conversations JS Quickstart does not implement them, you can find a list of webhooks that you can enable for your Conversations project. These webhooks include onMessageAdd, which is a pre-action webhook that could filter the text in the message, and onMessageAdded, which is a post-action webhook that could take action based on the contents of a message (such as updating a CRM).

The Conversations JS Quickstart also demonstrates how to send media, such as images, through the web browser interface using drag and drop. This functionality is in the Conversation.js(link takes you to an external page) file.

Sending a Message to a Conversation

sending-a-message-to-a-conversation page anchor
1
import React, { Component } from 'react';
2
import './assets/Conversation.css';
3
import MessageBubble from './MessageBubble'
4
import Dropzone from 'react-dropzone';
5
import styles from './assets/Conversation.module.css'
6
import {Button, Form, Icon, Input} from "antd";
7
import ConversationsMessages from "./ConversationsMessages";
8
import PropTypes from "prop-types";
9
10
class Conversation extends Component {
11
constructor(props) {
12
super(props);
13
this.state = {
14
newMessage: '',
15
conversationProxy: props.conversationProxy,
16
messages: [],
17
loadingState: 'initializing',
18
boundConversations: new Set()
19
};
20
}
21
22
loadMessagesFor = (thisConversation) => {
23
if (this.state.conversationProxy === thisConversation) {
24
thisConversation.getMessages()
25
.then(messagePaginator => {
26
if (this.state.conversationProxy === thisConversation) {
27
this.setState({ messages: messagePaginator.items, loadingState: 'ready' });
28
}
29
})
30
.catch(err => {
31
console.error("Couldn't fetch messages IMPLEMENT RETRY", err);
32
this.setState({ loadingState: "failed" });
33
});
34
}
35
};
36
37
componentDidMount = () => {
38
if (this.state.conversationProxy) {
39
this.loadMessagesFor(this.state.conversationProxy);
40
41
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
42
let newConversation = this.state.conversationProxy;
43
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
44
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
45
}
46
}
47
}
48
49
componentDidUpdate = (oldProps, oldState) => {
50
if (this.state.conversationProxy !== oldState.conversationProxy) {
51
this.loadMessagesFor(this.state.conversationProxy);
52
53
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
54
let newConversation = this.state.conversationProxy;
55
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
56
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
57
}
58
}
59
};
60
61
static getDerivedStateFromProps(newProps, oldState) {
62
let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;
63
if (logic) {
64
return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };
65
} else {
66
return null;
67
}
68
}
69
70
messageAdded = (message, targetConversation) => {
71
if (targetConversation === this.state.conversationProxy)
72
this.setState((prevState, props) => ({
73
messages: [...prevState.messages, message]
74
}));
75
};
76
77
onMessageChanged = event => {
78
this.setState({ newMessage: event.target.value });
79
};
80
81
sendMessage = event => {
82
event.preventDefault();
83
const message = this.state.newMessage;
84
this.setState({ newMessage: '' });
85
this.state.conversationProxy.sendMessage(message);
86
};
87
88
onDrop = acceptedFiles => {
89
this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});
90
};
91
92
render = () => {
93
return (
94
<Dropzone
95
onDrop={this.onDrop}
96
accept="image/*">
97
{({getRootProps, getInputProps, isDragActive}) => (
98
<div
99
{...getRootProps()}
100
onClick={() => {
101
}}
102
id="OpenChannel"
103
style={{position: "relative", top: 0}}>
104
105
{isDragActive &&
106
<div className={styles.drop}>
107
<Icon type={"cloud-upload"}
108
style={{fontSize: "5em", color: "#fefefe"}}/>
109
<h3 style={{color: "#fefefe"}}>Release to Upload</h3>
110
</div>
111
}
112
<div
113
className={styles.messages}
114
style={{
115
filter: `blur(${isDragActive ? 4 : 0}px)`,
116
}}
117
>
118
<input id="files" {...getInputProps()} />
119
<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>
120
<ConversationsMessages
121
identity={this.props.myIdentity}
122
messages={this.state.messages}/>
123
</div>
124
<div>
125
<Form onSubmit={this.sendMessage}>
126
<Input.Group compact={true} style={{
127
width: "100%",
128
display: "flex",
129
flexDirection: "row"
130
}}>
131
<Input
132
style={{flexBasis: "100%"}}
133
placeholder={"Type your message here..."}
134
type={"text"}
135
name={"message"}
136
id={styles['type-a-message']}
137
autoComplete={"off"}
138
disabled={this.state.loadingState !== 'ready'}
139
onChange={this.onMessageChanged}
140
value={this.state.newMessage}
141
/>
142
<Button icon="enter" htmlType="submit" type={"submit"}/>
143
</Input.Group>
144
</Form>
145
</div>
146
</div>
147
</div>
148
)}
149
150
</Dropzone>
151
);
152
}
153
}
154
155
Conversation.propTypes = {
156
myIdentity: PropTypes.string.isRequired
157
};
158
159
export default Conversation;

Receiving and Displaying Messages

receiving-and-displaying-messages page anchor

In the React Conversations demo, we created a Conversation React component, which you can find in the src/Conversation.js(link takes you to an external page) file in the GitHub repo. As part of that component, we listen to the messageAdded event on the SDK's Conversation object. To distinguish between the React component and the representation of a conversation in the Twilio SDK, we will call the SDK version a conversation proxy here. This conversation proxy gets passed into the React component as a property, and then the React component interacts with the SDK by calling methods on it, or adding listeners.

Displaying Existing Messages

displaying-existing-messages page anchor

The React Conversation component loads the existing messages from the conversation proxy, using the getMessages() method on the Twilio SDK Conversation class. This returns a paginator, and we load the messages from the first page of results up to display to the user when they join a conversation.

Conversations JS Quickstart - Conversation.js

conversations-js-quickstart---conversationjs page anchor
1
import React, { Component } from 'react';
2
import './assets/Conversation.css';
3
import MessageBubble from './MessageBubble'
4
import Dropzone from 'react-dropzone';
5
import styles from './assets/Conversation.module.css'
6
import {Button, Form, Icon, Input} from "antd";
7
import ConversationsMessages from "./ConversationsMessages";
8
import PropTypes from "prop-types";
9
10
class Conversation extends Component {
11
constructor(props) {
12
super(props);
13
this.state = {
14
newMessage: '',
15
conversationProxy: props.conversationProxy,
16
messages: [],
17
loadingState: 'initializing',
18
boundConversations: new Set()
19
};
20
}
21
22
loadMessagesFor = (thisConversation) => {
23
if (this.state.conversationProxy === thisConversation) {
24
thisConversation.getMessages()
25
.then(messagePaginator => {
26
if (this.state.conversationProxy === thisConversation) {
27
this.setState({ messages: messagePaginator.items, loadingState: 'ready' });
28
}
29
})
30
.catch(err => {
31
console.error("Couldn't fetch messages IMPLEMENT RETRY", err);
32
this.setState({ loadingState: "failed" });
33
});
34
}
35
};
36
37
componentDidMount = () => {
38
if (this.state.conversationProxy) {
39
this.loadMessagesFor(this.state.conversationProxy);
40
41
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
42
let newConversation = this.state.conversationProxy;
43
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
44
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
45
}
46
}
47
}
48
49
componentDidUpdate = (oldProps, oldState) => {
50
if (this.state.conversationProxy !== oldState.conversationProxy) {
51
this.loadMessagesFor(this.state.conversationProxy);
52
53
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
54
let newConversation = this.state.conversationProxy;
55
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
56
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
57
}
58
}
59
};
60
61
static getDerivedStateFromProps(newProps, oldState) {
62
let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;
63
if (logic) {
64
return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };
65
} else {
66
return null;
67
}
68
}
69
70
messageAdded = (message, targetConversation) => {
71
if (targetConversation === this.state.conversationProxy)
72
this.setState((prevState, props) => ({
73
messages: [...prevState.messages, message]
74
}));
75
};
76
77
onMessageChanged = event => {
78
this.setState({ newMessage: event.target.value });
79
};
80
81
sendMessage = event => {
82
event.preventDefault();
83
const message = this.state.newMessage;
84
this.setState({ newMessage: '' });
85
this.state.conversationProxy.sendMessage(message);
86
};
87
88
onDrop = acceptedFiles => {
89
this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});
90
};
91
92
render = () => {
93
return (
94
<Dropzone
95
onDrop={this.onDrop}
96
accept="image/*">
97
{({getRootProps, getInputProps, isDragActive}) => (
98
<div
99
{...getRootProps()}
100
onClick={() => {
101
}}
102
id="OpenChannel"
103
style={{position: "relative", top: 0}}>
104
105
{isDragActive &&
106
<div className={styles.drop}>
107
<Icon type={"cloud-upload"}
108
style={{fontSize: "5em", color: "#fefefe"}}/>
109
<h3 style={{color: "#fefefe"}}>Release to Upload</h3>
110
</div>
111
}
112
<div
113
className={styles.messages}
114
style={{
115
filter: `blur(${isDragActive ? 4 : 0}px)`,
116
}}
117
>
118
<input id="files" {...getInputProps()} />
119
<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>
120
<ConversationsMessages
121
identity={this.props.myIdentity}
122
messages={this.state.messages}/>
123
</div>
124
<div>
125
<Form onSubmit={this.sendMessage}>
126
<Input.Group compact={true} style={{
127
width: "100%",
128
display: "flex",
129
flexDirection: "row"
130
}}>
131
<Input
132
style={{flexBasis: "100%"}}
133
placeholder={"Type your message here..."}
134
type={"text"}
135
name={"message"}
136
id={styles['type-a-message']}
137
autoComplete={"off"}
138
disabled={this.state.loadingState !== 'ready'}
139
onChange={this.onMessageChanged}
140
value={this.state.newMessage}
141
/>
142
<Button icon="enter" htmlType="submit" type={"submit"}/>
143
</Input.Group>
144
</Form>
145
</div>
146
</div>
147
</div>
148
)}
149
150
</Dropzone>
151
);
152
}
153
}
154
155
Conversation.propTypes = {
156
myIdentity: PropTypes.string.isRequired
157
};
158
159
export default Conversation;

Displaying New Messages Added to the Conversation

displaying-new-messages-added-to-the-conversation page anchor

Using React also lets us handle the case where a new message gets added to the conversation. We listen to the messageAdded event from the Twilio Conversations SDK Conversation object, and then append that message to the messages we already have, and then set the state for the React component.

React handles the rendering for us as the messages list changes, which is much easier than trying to keep the DOM in sync with the message list manually.

Conversations JS Quickstart - Conversation.js

conversations-js-quickstart---conversationjs-1 page anchor
1
import React, { Component } from 'react';
2
import './assets/Conversation.css';
3
import MessageBubble from './MessageBubble'
4
import Dropzone from 'react-dropzone';
5
import styles from './assets/Conversation.module.css'
6
import {Button, Form, Icon, Input} from "antd";
7
import ConversationsMessages from "./ConversationsMessages";
8
import PropTypes from "prop-types";
9
10
class Conversation extends Component {
11
constructor(props) {
12
super(props);
13
this.state = {
14
newMessage: '',
15
conversationProxy: props.conversationProxy,
16
messages: [],
17
loadingState: 'initializing',
18
boundConversations: new Set()
19
};
20
}
21
22
loadMessagesFor = (thisConversation) => {
23
if (this.state.conversationProxy === thisConversation) {
24
thisConversation.getMessages()
25
.then(messagePaginator => {
26
if (this.state.conversationProxy === thisConversation) {
27
this.setState({ messages: messagePaginator.items, loadingState: 'ready' });
28
}
29
})
30
.catch(err => {
31
console.error("Couldn't fetch messages IMPLEMENT RETRY", err);
32
this.setState({ loadingState: "failed" });
33
});
34
}
35
};
36
37
componentDidMount = () => {
38
if (this.state.conversationProxy) {
39
this.loadMessagesFor(this.state.conversationProxy);
40
41
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
42
let newConversation = this.state.conversationProxy;
43
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
44
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
45
}
46
}
47
}
48
49
componentDidUpdate = (oldProps, oldState) => {
50
if (this.state.conversationProxy !== oldState.conversationProxy) {
51
this.loadMessagesFor(this.state.conversationProxy);
52
53
if (!this.state.boundConversations.has(this.state.conversationProxy)) {
54
let newConversation = this.state.conversationProxy;
55
newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));
56
this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});
57
}
58
}
59
};
60
61
static getDerivedStateFromProps(newProps, oldState) {
62
let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;
63
if (logic) {
64
return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };
65
} else {
66
return null;
67
}
68
}
69
70
messageAdded = (message, targetConversation) => {
71
if (targetConversation === this.state.conversationProxy)
72
this.setState((prevState, props) => ({
73
messages: [...prevState.messages, message]
74
}));
75
};
76
77
onMessageChanged = event => {
78
this.setState({ newMessage: event.target.value });
79
};
80
81
sendMessage = event => {
82
event.preventDefault();
83
const message = this.state.newMessage;
84
this.setState({ newMessage: '' });
85
this.state.conversationProxy.sendMessage(message);
86
};
87
88
onDrop = acceptedFiles => {
89
this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});
90
};
91
92
render = () => {
93
return (
94
<Dropzone
95
onDrop={this.onDrop}
96
accept="image/*">
97
{({getRootProps, getInputProps, isDragActive}) => (
98
<div
99
{...getRootProps()}
100
onClick={() => {
101
}}
102
id="OpenChannel"
103
style={{position: "relative", top: 0}}>
104
105
{isDragActive &&
106
<div className={styles.drop}>
107
<Icon type={"cloud-upload"}
108
style={{fontSize: "5em", color: "#fefefe"}}/>
109
<h3 style={{color: "#fefefe"}}>Release to Upload</h3>
110
</div>
111
}
112
<div
113
className={styles.messages}
114
style={{
115
filter: `blur(${isDragActive ? 4 : 0}px)`,
116
}}
117
>
118
<input id="files" {...getInputProps()} />
119
<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>
120
<ConversationsMessages
121
identity={this.props.myIdentity}
122
messages={this.state.messages}/>
123
</div>
124
<div>
125
<Form onSubmit={this.sendMessage}>
126
<Input.Group compact={true} style={{
127
width: "100%",
128
display: "flex",
129
flexDirection: "row"
130
}}>
131
<Input
132
style={{flexBasis: "100%"}}
133
placeholder={"Type your message here..."}
134
type={"text"}
135
name={"message"}
136
id={styles['type-a-message']}
137
autoComplete={"off"}
138
disabled={this.state.loadingState !== 'ready'}
139
onChange={this.onMessageChanged}
140
value={this.state.newMessage}
141
/>
142
<Button icon="enter" htmlType="submit" type={"submit"}/>
143
</Input.Group>
144
</Form>
145
</div>
146
</div>
147
</div>
148
)}
149
150
</Dropzone>
151
);
152
}
153
}
154
155
Conversation.propTypes = {
156
myIdentity: PropTypes.string.isRequired
157
};
158
159
export default Conversation;

Now that you've seen how the Conversations JavaScript Quickstart implements several key pieces of functionality, you can see how to add the Conversations SDK to your React or JavaScript project. You can re-use these React components within your own web application's front end. If you're using Angular or Vue, some of the patterns in this React project should be applicable to your solution.

For more information, check out these helpful links:

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.