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.
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 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, Vue, or any other JavaScript framework for the web browser.
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.
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"2integrity="sha256-v2SFLWujVq0wnwHpcxct7bzTP8wII7sumEhAKMEqgHQ="3crossorigin="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. 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.
If you don't already have a Twilio account, sign up for a Twilio trial account, 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.
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).
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.
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 to learn a lot more about this topic!
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:
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.
1import React from "react";2import { Badge, Icon, Layout, Spin, Typography } from "antd";3import { Client as ConversationsClient } from "@twilio/conversations";45import "./assets/Conversation.css";6import "./assets/ConversationSection.css";7import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";89import Conversation from "./Conversation";10import LoginPage from "./LoginPage";11import { ConversationsList } from "./ConversationsList";12import { HeaderItem } from "./HeaderItem";1314const { Content, Sider, Header } = Layout;15const { Text } = Typography;1617class ConversationsApp extends React.Component {18constructor(props) {19super(props);2021const name = localStorage.getItem("name") || "";22const loggedIn = name !== "";2324this.state = {25name,26loggedIn,27token: null,28statusString: null,29conversationsReady: false,30conversations: [],31selectedConversationSid: null,32newMessage: ""33};34}3536componentDidMount = () => {37if (this.state.loggedIn) {38this.getToken();39this.setState({ statusString: "Fetching credentials…" });40}41};4243logIn = (name) => {44if (name !== "") {45localStorage.setItem("name", name);46this.setState({ name, loggedIn: true }, this.getToken);47}48};4950logOut = (event) => {51if (event) {52event.preventDefault();53}5455this.setState({56name: "",57loggedIn: false,58token: "",59conversationsReady: false,60messages: [],61newMessage: "",62conversations: []63});6465localStorage.removeItem("name");66this.conversationsClient.shutdown();67};6869getToken = () => {70// Paste your unique Chat token function71const myToken = "<Your token here>";72this.setState({ token: myToken }, this.initConversations);73};7475initConversations = async () => {76window.conversationsClient = ConversationsClient;77this.conversationsClient = new ConversationsClient(this.state.token);78this.setState({ statusString: "Connecting to Twilio…" });7980this.conversationsClient.on("connectionStateChanged", (state) => {81if (state === "connecting")82this.setState({83statusString: "Connecting to Twilio…",84status: "default"85});86if (state === "connected") {87this.setState({88statusString: "You are connected.",89status: "success"90});91}92if (state === "disconnecting")93this.setState({94statusString: "Disconnecting from Twilio…",95conversationsReady: false,96status: "default"97});98if (state === "disconnected")99this.setState({100statusString: "Disconnected.",101conversationsReady: false,102status: "warning"103});104if (state === "denied")105this.setState({106statusString: "Failed to connect.",107conversationsReady: false,108status: "error"109});110});111this.conversationsClient.on("conversationJoined", (conversation) => {112this.setState({ conversations: [...this.state.conversations, conversation] });113});114this.conversationsClient.on("conversationLeft", (thisConversation) => {115this.setState({116conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]117});118});119};120121render() {122const { conversations, selectedConversationSid, status } = this.state;123const selectedConversation = conversations.find(124(it) => it.sid === selectedConversationSid125);126127let conversationContent;128if (selectedConversation) {129conversationContent = (130<Conversation131conversationProxy={selectedConversation}132myIdentity={this.state.name}133/>134);135} else if (status !== "success") {136conversationContent = "Loading your conversation!";137} else {138conversationContent = "";139}140141if (this.state.loggedIn) {142return (143<div className="conversations-window-wrapper">144<Layout className="conversations-window-container">145<Header146style={{ display: "flex", alignItems: "center", padding: 0 }}147>148<div149style={{150maxWidth: "250px",151width: "100%",152display: "flex",153alignItems: "center"154}}155>156<HeaderItem style={{ paddingRight: "0", display: "flex" }}>157<Logo />158</HeaderItem>159<HeaderItem>160<Text strong style={{ color: "white" }}>161Conversations162</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<span174style={{ color: "white" }}175>{` ${this.state.statusString}`}</span>176<Badge177dot={true}178status={this.state.status}179style={{ marginLeft: "1em" }}180/>181</HeaderItem>182<HeaderItem>183<Icon184type="poweroff"185onClick={this.logOut}186style={{187color: "white",188fontSize: "20px",189marginLeft: "auto"190}}191/>192</HeaderItem>193</div>194</Header>195<Layout>196<Sider theme={"light"} width={250}>197<ConversationsList198conversations={conversations}199selectedConversationSid={selectedConversationSid}200onConversationClick={(item) => {201this.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}213214return <LoginPage onSubmit={this.logIn} />;215}216}217218export 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.
1import React from "react";2import { Badge, Icon, Layout, Spin, Typography } from "antd";3import { Client as ConversationsClient } from "@twilio/conversations";45import "./assets/Conversation.css";6import "./assets/ConversationSection.css";7import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";89import Conversation from "./Conversation";10import LoginPage from "./LoginPage";11import { ConversationsList } from "./ConversationsList";12import { HeaderItem } from "./HeaderItem";1314const { Content, Sider, Header } = Layout;15const { Text } = Typography;1617class ConversationsApp extends React.Component {18constructor(props) {19super(props);2021const name = localStorage.getItem("name") || "";22const loggedIn = name !== "";2324this.state = {25name,26loggedIn,27token: null,28statusString: null,29conversationsReady: false,30conversations: [],31selectedConversationSid: null,32newMessage: ""33};34}3536componentDidMount = () => {37if (this.state.loggedIn) {38this.getToken();39this.setState({ statusString: "Fetching credentials…" });40}41};4243logIn = (name) => {44if (name !== "") {45localStorage.setItem("name", name);46this.setState({ name, loggedIn: true }, this.getToken);47}48};4950logOut = (event) => {51if (event) {52event.preventDefault();53}5455this.setState({56name: "",57loggedIn: false,58token: "",59conversationsReady: false,60messages: [],61newMessage: "",62conversations: []63});6465localStorage.removeItem("name");66this.conversationsClient.shutdown();67};6869getToken = () => {70// Paste your unique Chat token function71const myToken = "<Your token here>";72this.setState({ token: myToken }, this.initConversations);73};7475initConversations = async () => {76window.conversationsClient = ConversationsClient;77this.conversationsClient = new ConversationsClient(this.state.token);78this.setState({ statusString: "Connecting to Twilio…" });7980this.conversationsClient.on("connectionStateChanged", (state) => {81if (state === "connecting")82this.setState({83statusString: "Connecting to Twilio…",84status: "default"85});86if (state === "connected") {87this.setState({88statusString: "You are connected.",89status: "success"90});91}92if (state === "disconnecting")93this.setState({94statusString: "Disconnecting from Twilio…",95conversationsReady: false,96status: "default"97});98if (state === "disconnected")99this.setState({100statusString: "Disconnected.",101conversationsReady: false,102status: "warning"103});104if (state === "denied")105this.setState({106statusString: "Failed to connect.",107conversationsReady: false,108status: "error"109});110});111this.conversationsClient.on("conversationJoined", (conversation) => {112this.setState({ conversations: [...this.state.conversations, conversation] });113});114this.conversationsClient.on("conversationLeft", (thisConversation) => {115this.setState({116conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]117});118});119};120121render() {122const { conversations, selectedConversationSid, status } = this.state;123const selectedConversation = conversations.find(124(it) => it.sid === selectedConversationSid125);126127let conversationContent;128if (selectedConversation) {129conversationContent = (130<Conversation131conversationProxy={selectedConversation}132myIdentity={this.state.name}133/>134);135} else if (status !== "success") {136conversationContent = "Loading your conversation!";137} else {138conversationContent = "";139}140141if (this.state.loggedIn) {142return (143<div className="conversations-window-wrapper">144<Layout className="conversations-window-container">145<Header146style={{ display: "flex", alignItems: "center", padding: 0 }}147>148<div149style={{150maxWidth: "250px",151width: "100%",152display: "flex",153alignItems: "center"154}}155>156<HeaderItem style={{ paddingRight: "0", display: "flex" }}>157<Logo />158</HeaderItem>159<HeaderItem>160<Text strong style={{ color: "white" }}>161Conversations162</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<span174style={{ color: "white" }}175>{` ${this.state.statusString}`}</span>176<Badge177dot={true}178status={this.state.status}179style={{ marginLeft: "1em" }}180/>181</HeaderItem>182<HeaderItem>183<Icon184type="poweroff"185onClick={this.logOut}186style={{187color: "white",188fontSize: "20px",189marginLeft: "auto"190}}191/>192</HeaderItem>193</div>194</Header>195<Layout>196<Sider theme={"light"} width={250}>197<ConversationsList198conversations={conversations}199selectedConversationSid={selectedConversationSid}200onConversationClick={(item) => {201this.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}213214return <LoginPage onSubmit={this.logIn} />;215}216}217218export default ConversationsApp;
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
component.
1import React from "react";2import { Badge, Icon, Layout, Spin, Typography } from "antd";3import { Client as ConversationsClient } from "@twilio/conversations";45import "./assets/Conversation.css";6import "./assets/ConversationSection.css";7import { ReactComponent as Logo } from "./assets/twilio-mark-red.svg";89import Conversation from "./Conversation";10import LoginPage from "./LoginPage";11import { ConversationsList } from "./ConversationsList";12import { HeaderItem } from "./HeaderItem";1314const { Content, Sider, Header } = Layout;15const { Text } = Typography;1617class ConversationsApp extends React.Component {18constructor(props) {19super(props);2021const name = localStorage.getItem("name") || "";22const loggedIn = name !== "";2324this.state = {25name,26loggedIn,27token: null,28statusString: null,29conversationsReady: false,30conversations: [],31selectedConversationSid: null,32newMessage: ""33};34}3536componentDidMount = () => {37if (this.state.loggedIn) {38this.getToken();39this.setState({ statusString: "Fetching credentials…" });40}41};4243logIn = (name) => {44if (name !== "") {45localStorage.setItem("name", name);46this.setState({ name, loggedIn: true }, this.getToken);47}48};4950logOut = (event) => {51if (event) {52event.preventDefault();53}5455this.setState({56name: "",57loggedIn: false,58token: "",59conversationsReady: false,60messages: [],61newMessage: "",62conversations: []63});6465localStorage.removeItem("name");66this.conversationsClient.shutdown();67};6869getToken = () => {70// Paste your unique Chat token function71const myToken = "<Your token here>";72this.setState({ token: myToken }, this.initConversations);73};7475initConversations = async () => {76window.conversationsClient = ConversationsClient;77this.conversationsClient = new ConversationsClient(this.state.token);78this.setState({ statusString: "Connecting to Twilio…" });7980this.conversationsClient.on("connectionStateChanged", (state) => {81if (state === "connecting")82this.setState({83statusString: "Connecting to Twilio…",84status: "default"85});86if (state === "connected") {87this.setState({88statusString: "You are connected.",89status: "success"90});91}92if (state === "disconnecting")93this.setState({94statusString: "Disconnecting from Twilio…",95conversationsReady: false,96status: "default"97});98if (state === "disconnected")99this.setState({100statusString: "Disconnected.",101conversationsReady: false,102status: "warning"103});104if (state === "denied")105this.setState({106statusString: "Failed to connect.",107conversationsReady: false,108status: "error"109});110});111this.conversationsClient.on("conversationJoined", (conversation) => {112this.setState({ conversations: [...this.state.conversations, conversation] });113});114this.conversationsClient.on("conversationLeft", (thisConversation) => {115this.setState({116conversations: [...this.state.conversations.filter((it) => it !== thisConversation)]117});118});119};120121render() {122const { conversations, selectedConversationSid, status } = this.state;123const selectedConversation = conversations.find(124(it) => it.sid === selectedConversationSid125);126127let conversationContent;128if (selectedConversation) {129conversationContent = (130<Conversation131conversationProxy={selectedConversation}132myIdentity={this.state.name}133/>134);135} else if (status !== "success") {136conversationContent = "Loading your conversation!";137} else {138conversationContent = "";139}140141if (this.state.loggedIn) {142return (143<div className="conversations-window-wrapper">144<Layout className="conversations-window-container">145<Header146style={{ display: "flex", alignItems: "center", padding: 0 }}147>148<div149style={{150maxWidth: "250px",151width: "100%",152display: "flex",153alignItems: "center"154}}155>156<HeaderItem style={{ paddingRight: "0", display: "flex" }}>157<Logo />158</HeaderItem>159<HeaderItem>160<Text strong style={{ color: "white" }}>161Conversations162</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<span174style={{ color: "white" }}175>{` ${this.state.statusString}`}</span>176<Badge177dot={true}178status={this.state.status}179style={{ marginLeft: "1em" }}180/>181</HeaderItem>182<HeaderItem>183<Icon184type="poweroff"185onClick={this.logOut}186style={{187color: "white",188fontSize: "20px",189marginLeft: "auto"190}}191/>192</HeaderItem>193</div>194</Header>195<Layout>196<Sider theme={"light"} width={250}>197<ConversationsList198conversations={conversations}199selectedConversationSid={selectedConversationSid}200onConversationClick={(item) => {201this.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}213214return <LoginPage onSubmit={this.logIn} />;215}216}217218export default ConversationsApp;
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 file.
1import React, { Component } from 'react';2import './assets/Conversation.css';3import MessageBubble from './MessageBubble'4import Dropzone from 'react-dropzone';5import styles from './assets/Conversation.module.css'6import {Button, Form, Icon, Input} from "antd";7import ConversationsMessages from "./ConversationsMessages";8import PropTypes from "prop-types";910class Conversation extends Component {11constructor(props) {12super(props);13this.state = {14newMessage: '',15conversationProxy: props.conversationProxy,16messages: [],17loadingState: 'initializing',18boundConversations: new Set()19};20}2122loadMessagesFor = (thisConversation) => {23if (this.state.conversationProxy === thisConversation) {24thisConversation.getMessages()25.then(messagePaginator => {26if (this.state.conversationProxy === thisConversation) {27this.setState({ messages: messagePaginator.items, loadingState: 'ready' });28}29})30.catch(err => {31console.error("Couldn't fetch messages IMPLEMENT RETRY", err);32this.setState({ loadingState: "failed" });33});34}35};3637componentDidMount = () => {38if (this.state.conversationProxy) {39this.loadMessagesFor(this.state.conversationProxy);4041if (!this.state.boundConversations.has(this.state.conversationProxy)) {42let newConversation = this.state.conversationProxy;43newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));44this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});45}46}47}4849componentDidUpdate = (oldProps, oldState) => {50if (this.state.conversationProxy !== oldState.conversationProxy) {51this.loadMessagesFor(this.state.conversationProxy);5253if (!this.state.boundConversations.has(this.state.conversationProxy)) {54let newConversation = this.state.conversationProxy;55newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));56this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});57}58}59};6061static getDerivedStateFromProps(newProps, oldState) {62let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;63if (logic) {64return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };65} else {66return null;67}68}6970messageAdded = (message, targetConversation) => {71if (targetConversation === this.state.conversationProxy)72this.setState((prevState, props) => ({73messages: [...prevState.messages, message]74}));75};7677onMessageChanged = event => {78this.setState({ newMessage: event.target.value });79};8081sendMessage = event => {82event.preventDefault();83const message = this.state.newMessage;84this.setState({ newMessage: '' });85this.state.conversationProxy.sendMessage(message);86};8788onDrop = acceptedFiles => {89this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});90};9192render = () => {93return (94<Dropzone95onDrop={this.onDrop}96accept="image/*">97{({getRootProps, getInputProps, isDragActive}) => (98<div99{...getRootProps()}100onClick={() => {101}}102id="OpenChannel"103style={{position: "relative", top: 0}}>104105{isDragActive &&106<div className={styles.drop}>107<Icon type={"cloud-upload"}108style={{fontSize: "5em", color: "#fefefe"}}/>109<h3 style={{color: "#fefefe"}}>Release to Upload</h3>110</div>111}112<div113className={styles.messages}114style={{115filter: `blur(${isDragActive ? 4 : 0}px)`,116}}117>118<input id="files" {...getInputProps()} />119<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>120<ConversationsMessages121identity={this.props.myIdentity}122messages={this.state.messages}/>123</div>124<div>125<Form onSubmit={this.sendMessage}>126<Input.Group compact={true} style={{127width: "100%",128display: "flex",129flexDirection: "row"130}}>131<Input132style={{flexBasis: "100%"}}133placeholder={"Type your message here..."}134type={"text"}135name={"message"}136id={styles['type-a-message']}137autoComplete={"off"}138disabled={this.state.loadingState !== 'ready'}139onChange={this.onMessageChanged}140value={this.state.newMessage}141/>142<Button icon="enter" htmlType="submit" type={"submit"}/>143</Input.Group>144</Form>145</div>146</div>147</div>148)}149150</Dropzone>151);152}153}154155Conversation.propTypes = {156myIdentity: PropTypes.string.isRequired157};158159export default Conversation;
In the React Conversations demo, we created a Conversation
React component, which you can find in the src/Conversation.js 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.
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.
1import React, { Component } from 'react';2import './assets/Conversation.css';3import MessageBubble from './MessageBubble'4import Dropzone from 'react-dropzone';5import styles from './assets/Conversation.module.css'6import {Button, Form, Icon, Input} from "antd";7import ConversationsMessages from "./ConversationsMessages";8import PropTypes from "prop-types";910class Conversation extends Component {11constructor(props) {12super(props);13this.state = {14newMessage: '',15conversationProxy: props.conversationProxy,16messages: [],17loadingState: 'initializing',18boundConversations: new Set()19};20}2122loadMessagesFor = (thisConversation) => {23if (this.state.conversationProxy === thisConversation) {24thisConversation.getMessages()25.then(messagePaginator => {26if (this.state.conversationProxy === thisConversation) {27this.setState({ messages: messagePaginator.items, loadingState: 'ready' });28}29})30.catch(err => {31console.error("Couldn't fetch messages IMPLEMENT RETRY", err);32this.setState({ loadingState: "failed" });33});34}35};3637componentDidMount = () => {38if (this.state.conversationProxy) {39this.loadMessagesFor(this.state.conversationProxy);4041if (!this.state.boundConversations.has(this.state.conversationProxy)) {42let newConversation = this.state.conversationProxy;43newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));44this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});45}46}47}4849componentDidUpdate = (oldProps, oldState) => {50if (this.state.conversationProxy !== oldState.conversationProxy) {51this.loadMessagesFor(this.state.conversationProxy);5253if (!this.state.boundConversations.has(this.state.conversationProxy)) {54let newConversation = this.state.conversationProxy;55newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));56this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});57}58}59};6061static getDerivedStateFromProps(newProps, oldState) {62let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;63if (logic) {64return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };65} else {66return null;67}68}6970messageAdded = (message, targetConversation) => {71if (targetConversation === this.state.conversationProxy)72this.setState((prevState, props) => ({73messages: [...prevState.messages, message]74}));75};7677onMessageChanged = event => {78this.setState({ newMessage: event.target.value });79};8081sendMessage = event => {82event.preventDefault();83const message = this.state.newMessage;84this.setState({ newMessage: '' });85this.state.conversationProxy.sendMessage(message);86};8788onDrop = acceptedFiles => {89this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});90};9192render = () => {93return (94<Dropzone95onDrop={this.onDrop}96accept="image/*">97{({getRootProps, getInputProps, isDragActive}) => (98<div99{...getRootProps()}100onClick={() => {101}}102id="OpenChannel"103style={{position: "relative", top: 0}}>104105{isDragActive &&106<div className={styles.drop}>107<Icon type={"cloud-upload"}108style={{fontSize: "5em", color: "#fefefe"}}/>109<h3 style={{color: "#fefefe"}}>Release to Upload</h3>110</div>111}112<div113className={styles.messages}114style={{115filter: `blur(${isDragActive ? 4 : 0}px)`,116}}117>118<input id="files" {...getInputProps()} />119<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>120<ConversationsMessages121identity={this.props.myIdentity}122messages={this.state.messages}/>123</div>124<div>125<Form onSubmit={this.sendMessage}>126<Input.Group compact={true} style={{127width: "100%",128display: "flex",129flexDirection: "row"130}}>131<Input132style={{flexBasis: "100%"}}133placeholder={"Type your message here..."}134type={"text"}135name={"message"}136id={styles['type-a-message']}137autoComplete={"off"}138disabled={this.state.loadingState !== 'ready'}139onChange={this.onMessageChanged}140value={this.state.newMessage}141/>142<Button icon="enter" htmlType="submit" type={"submit"}/>143</Input.Group>144</Form>145</div>146</div>147</div>148)}149150</Dropzone>151);152}153}154155Conversation.propTypes = {156myIdentity: PropTypes.string.isRequired157};158159export default Conversation;
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.
1import React, { Component } from 'react';2import './assets/Conversation.css';3import MessageBubble from './MessageBubble'4import Dropzone from 'react-dropzone';5import styles from './assets/Conversation.module.css'6import {Button, Form, Icon, Input} from "antd";7import ConversationsMessages from "./ConversationsMessages";8import PropTypes from "prop-types";910class Conversation extends Component {11constructor(props) {12super(props);13this.state = {14newMessage: '',15conversationProxy: props.conversationProxy,16messages: [],17loadingState: 'initializing',18boundConversations: new Set()19};20}2122loadMessagesFor = (thisConversation) => {23if (this.state.conversationProxy === thisConversation) {24thisConversation.getMessages()25.then(messagePaginator => {26if (this.state.conversationProxy === thisConversation) {27this.setState({ messages: messagePaginator.items, loadingState: 'ready' });28}29})30.catch(err => {31console.error("Couldn't fetch messages IMPLEMENT RETRY", err);32this.setState({ loadingState: "failed" });33});34}35};3637componentDidMount = () => {38if (this.state.conversationProxy) {39this.loadMessagesFor(this.state.conversationProxy);4041if (!this.state.boundConversations.has(this.state.conversationProxy)) {42let newConversation = this.state.conversationProxy;43newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));44this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});45}46}47}4849componentDidUpdate = (oldProps, oldState) => {50if (this.state.conversationProxy !== oldState.conversationProxy) {51this.loadMessagesFor(this.state.conversationProxy);5253if (!this.state.boundConversations.has(this.state.conversationProxy)) {54let newConversation = this.state.conversationProxy;55newConversation.on('messageAdded', m => this.messageAdded(m, newConversation));56this.setState({boundConversations: new Set([...this.state.boundConversations, newConversation])});57}58}59};6061static getDerivedStateFromProps(newProps, oldState) {62let logic = (oldState.loadingState === 'initializing') || oldState.conversationProxy !== newProps.conversationProxy;63if (logic) {64return { loadingState: 'loading messages', conversationProxy: newProps.conversationProxy };65} else {66return null;67}68}6970messageAdded = (message, targetConversation) => {71if (targetConversation === this.state.conversationProxy)72this.setState((prevState, props) => ({73messages: [...prevState.messages, message]74}));75};7677onMessageChanged = event => {78this.setState({ newMessage: event.target.value });79};8081sendMessage = event => {82event.preventDefault();83const message = this.state.newMessage;84this.setState({ newMessage: '' });85this.state.conversationProxy.sendMessage(message);86};8788onDrop = acceptedFiles => {89this.state.conversationProxy.sendMessage({contentType: acceptedFiles[0].type, media: acceptedFiles[0]});90};9192render = () => {93return (94<Dropzone95onDrop={this.onDrop}96accept="image/*">97{({getRootProps, getInputProps, isDragActive}) => (98<div99{...getRootProps()}100onClick={() => {101}}102id="OpenChannel"103style={{position: "relative", top: 0}}>104105{isDragActive &&106<div className={styles.drop}>107<Icon type={"cloud-upload"}108style={{fontSize: "5em", color: "#fefefe"}}/>109<h3 style={{color: "#fefefe"}}>Release to Upload</h3>110</div>111}112<div113className={styles.messages}114style={{115filter: `blur(${isDragActive ? 4 : 0}px)`,116}}117>118<input id="files" {...getInputProps()} />119<div style={{flexBasis: "100%", flexGrow: 2, flexShrink: 1, overflowY: "scroll"}}>120<ConversationsMessages121identity={this.props.myIdentity}122messages={this.state.messages}/>123</div>124<div>125<Form onSubmit={this.sendMessage}>126<Input.Group compact={true} style={{127width: "100%",128display: "flex",129flexDirection: "row"130}}>131<Input132style={{flexBasis: "100%"}}133placeholder={"Type your message here..."}134type={"text"}135name={"message"}136id={styles['type-a-message']}137autoComplete={"off"}138disabled={this.state.loadingState !== 'ready'}139onChange={this.onMessageChanged}140value={this.state.newMessage}141/>142<Button icon="enter" htmlType="submit" type={"submit"}/>143</Input.Group>144</Form>145</div>146</div>147</div>148)}149150</Dropzone>151);152}153}154155Conversation.propTypes = {156myIdentity: PropTypes.string.isRequired157};158159export 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: