provides an SDK and robust back-end for real time chat applications, but it’s missing a front-end. If you need a chat UI, as well as a whole bunch of other useful components, then might be what you’re looking for. Twilio Programmable Chat KendoReact Kendo UI provides well designed and tested components that you can use within your , , and applications. In this post we will build a Twilio Chat application with React and the components. React Angular Vue jQuery KendoReact conversational UI What you’ll need If you want to build along with this tutorial, then you’ll need a few things: A Twilio account (you can ) sign up for a Twilio account for free here A and an , both of which you can create in the (keep these nearby, you’ll need them soon) Twilio Chat service API key and secret Twilio console to build our React app and to run our server (we need a server to generate access tokens to authenticate our users with Twilio Programmable Chat) Node.js If you want to skip ahead, you can check out . the code for this application in this GitHub repo Let’s get started We’re going to use the that I built in as the basis for this app. This app gives us an easy way to run a Node.js server and React front-end with one command and comes with endpoints ready to create Access Tokens for Twilio Programmable Chat. or clone the application, change into the directory, and install the dependencies: React and Express starter application this post Download git clone -b twilio https://github.com/philnash/react-express-starter.git twilio-chat-kendocd twilio-chat-kendonpm install Copy the file to then fill in the blanks with your Twilio account SID, the chat service, and API keys you generated earlier. .env.example .env cp .env.example .env Run the application to make sure everything is working so far. On the command line run: npm run dev You will see an application that looks like this open in your browser at localhost:3000. We have our Twilio Chat application ready and our React app set up. Let’s get building. Preparing to chat There’s a bit of work we need to do before we start on the chat integration. We need to install some dependencies, remove the example app, and add a bit of style. Let’s start with those dependencies. We’ll need the module to connect with Twilio Chat and then a few KendoReact modules that will provide the components we're going to use: twilio-chat npm install twilio-chat @progress/kendo-react-conversational-ui \@progress/kendo-react-inputs @progress/kendo-react-buttons \@progress/kendo-react-intl @progress/kendo-theme-material Next, strip back to the basics, including the CSS for the KendoReact Material theme: src/App.js import React, { Component } from 'react';import '@progress/kendo-theme-material/dist/all.css'; class App extends Component {constructor(props) {super(props);} render() {return <p>Hello world</p>;}} export default App; To give the application a bit more style and layout (without too much effort) add the Bootstrap CSS to the of : <head> public/index.html <!DOCTYPE html><html lang="en"><head><!-- rest of the head --><title>React App</title><linkrel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"crossorigin="anonymous"/></head> With that done it’s time to build our first component. Building a login form For users to join our chat we need them to log in and choose a username. If you are building this into an existing application, you probably already have users and a login system. For this post we’re just going to fake it by presenting a login form that asks for a username. Create a new file, , and open it up. We'll make this a as the login form itself doesn't need to store any state. Start with the following boilerplate: src/Login.js functional component import React from 'react'; const Login = props => {return;};export default Login; To make our Login form fit in with our conversational UI, we’ll use KendoReact components. At the top import the and components: Button Input import React from 'react';import { Button } from '@progress/kendo-react-buttons';import { Input } from '@progress/kendo-react-inputs'; Modify the function to return the following JSX: Login const Login = props => {return (<form className="k-form" onSubmit={props.handleLogin}><fieldset><legend>Log in</legend><div className="mb-3"><Inputname="username"label="Username"required={true}style={{ width: '100%' }}value={props.username}onChange={props.handleUsernameChange}/></div><div><Button type="submit" primary={true}>Sign in</Button></div></fieldset></form>);}; That’s quite the chunk of JSX, so let’s break it down. The whole thing is a containing a and . Then inside there is an component and a component. These are the KendoReact components that we imported. They act like regular and elements but fit in with the KendoReact style. <form> <fieldset> <legend> <Input> <Button> <input> <button> The JSX also includes some properties we need to provide the component with; a username and two functions to handle events. We’ll add these to the component so we can pass them in as properties. <App> Open up and start by importing the new component. src/App.js <Login> import React, { Component } from 'react';import '@progress/kendo-theme-material/dist/all.css';import Login from './Login'; Define the two functions that we’ll be passing to the component. One function needs to handle the user typing in the input and update the username stored in the state. The other handles the form being submitted and will set the state to show that the user is logged in. Add these below the component's constructor in : <Login> <App> src/App.js handleLogin(event) {event.preventDefault();this.setState({ loggedIn: true });}handleUsernameChange(event) {this.setState({ username: event.target.value });} In the constructor we need to initialise the state and bind these functions to the component: constructor(props) {super(props);this.state = {username: '',loggedIn: false};this.handleLogin = this.handleLogin.bind(this);this.handleUsernameChange = this.handleUsernameChange.bind(this);} Now let’s update the function to show the username if the state says the user is logged in, and the component otherwise. render <Login> render() {let loginOrChat;if (this.state.loggedIn) {loginOrChat = <p>Logged in as {this.state.username}</p>;} else {loginOrChat = (<LoginhandleLogin={this.handleLogin}handleUsernameChange={this.handleUsernameChange}username={this.state.username}/>);}return (<div className="container"><div className="row mt-3 justify-content-center">{loginOrChat}</div></div>);} If your application is still running, return to the browser and you will see the login form. Otherwise start the app with and open . Enter your name in the form and press enter or click "Sign in". npm run dev localhost:3000 Hooking up Programmable Chat Now we can use the username to generate an access token, and connect our logged in user with chat. Create a new file called and open it up. We'll create a class based component for the chat app, so add the following boilerplate: src/ChatApp.js import React, { Component } from 'react'; class ChatApp extends Component {} export default ChatApp; There are a few things we need to do in this component: Retrieve an access token from the server and initialise the Twilio Chat client Setup a chat channel and join it, loading any existing messages Create a function to send a message Render the KendoReact Conversational UI Before any of that we’ll need to import two modules; twilio-chat and the KendoReact conversationalUI. At the top of add: src/ChatApp.js import React, { Component } from 'react';import Chat from 'twilio-chat';import { Chat as ChatUI } from '@progress/kendo-react-conversational-ui'; Let’s set up some initial state in the constructor too. We’ll need a list of messages, an error state in case anything goes wrong, and a boolean to show if the chat is loading, which will start as . true class ChatApp extends Component {constructor(props) {super(props);this.state = {error: null,isLoading: true,messages: []};}} Getting an access token The starter project is already setup to return a token when we pass an identity to the endpoint. We'll use the API to make the request as part of the lifecycle event. We use here as the React documentation tells us that this is a good place to load external data. /chat/token fetch componentDidMount componentDidMount The response with the access token will be JSON, so we’ll need to parse it using the response object’s method then once it's parsed, we can use the token to initialise the Chat client. json Creating the Chat client returns a promise so we can chain all these methods. Once the Chat client is created we will pass off to another method to finish the setup. We should also handle any errors with a method. catch Add this code to the class below the constructor: ChatApp componentDidMount() {fetch('/chat/token', {headers: { 'Content-Type': 'application/x-www-form-urlencoded' },method: 'POST',body: `identity=${encodeURIComponent(this.props.username)}`}).then(res => res.json()).then(data => Chat.create(data.token)).then(this.setupChatClient).catch(this.handleError);} Write the method to handle the error. We’ll set a message in the state and log the full error so we can debug if we have any trouble. handleError(error) {console.error(error);this.setState({error: 'Could not load chat.'});} Setting up a Chat channel We’ve initialised our Chat client with an access token but there’s more to do. Once the promise resolves we need to use the new chat client to join a channel. As this is our first time through the process we’ll check to see if the channel exists. If so, we’ll attempt to join it; otherwise, we’ll create it then join it. Add the following method to the class: setupChatClient setupChatClient(client) {this.client = client;this.client.getChannelByUniqueName('general').then(channel => channel).catch(error => {if (error.body.code === 50300) {return this.client.createChannel({ uniqueName: 'general' });} else {this.handleError(error);}}).then(channel => {this.channel = channel;return this.channel.join().catch(() => {});}).then(() => {// Success!}).catch(this.handleError);} We catch the error in the middle in case the channel doesn’t exist (a 50300 error) and create the channel. Also, if joining a channel throws an error we catch it and do nothing. This handles the case when the user is already a member of the channel. If everything works the code will get to the success comment. At this stage the channel has loaded, so we can set our state variable to . We also need to load existing messages and set up a listener for new messages. isLoading false Replace the comment above with: // Success! .then(() => { this.setState({ isLoading: false }); this.channel.getMessages().then(this.messagesLoaded); this.channel.on('messageAdded', this.messageAdded); }) Receiving Messages We need to write the and methods we just referenced above, but before we do we need to consider the . We need to translate the message object from the format Twilio provides it to that which can be used by the conversational UI component. messagesLoaded messageAdded format that the KendoReact conversational UI wants the messages Let’s write a function that can take a and return a message object for KendoReact: message from the Chat service twilioMessageToKendoMessage(message) {return {text: message.body,author: { id: message.author, name: message.author },timestamp: message.timestamp};} Now we can write the and methods. runs when we first load the existing messages to a channel so we fill up with all the messages we receive. messagesLoaded messageAdded messagesLoaded state.messages messagesLoaded(messagePage) {this.setState({messages: messagePage.items.map(this.twilioMessageToKendoMessage)});} will receive one message as its argument so we use the callback version of to add the message to the list. Note we also use the spread operator ( ) to copy the existing messages into the new state. messageAdded [setState](https://reactjs.org/docs/react-component.html#setstate) ... messageAdded(message) {this.setState(prevState => ({messages: [...prevState.messages,this.twilioMessageToKendoMessage(message)]}));} Sending messages We also need a function to send a message to a channel. This function will be called by the KendoReact Conversational UI when a user types a message in the message box and sends it by clicking the send button or pressing enter. To handle it, we need to send the message text onto the channel. Displaying the message will be handled by the existing event we are listening to on the channel. messageAdded Add the following function to the class: ChatApp sendMessage(event) {this.channel.sendMessage(event.message.text);} Tidying up and rendering the Conversational UI We have some final parts to complete before we can see the chat in action. We should handle the component being unmounted. We can do this by shutting the chat client instance down. componentWillUnmount() {this.client.shutdown();} The Conversational UI expects a user object, which we will create using our user identity. We also need to bind all of our callback functions to the component. Add the following to the constructor: constructor(props) {super(props); this.state = { error: null, isLoading: true, messages: \[\] }; this.user = { id: props.username, name: props.username }; this.setupChatClient = this.setupChatClient.bind(this); this.messagesLoaded = this.messagesLoaded.bind(this); this.messageAdded = this.messageAdded.bind(this); this.sendMessage = this.sendMessage.bind(this); this.handleError = this.handleError.bind(this); } Rendering the chat Now we have everything in place we can render the Conversational UI. Create a method in that handles the various states of the component. If there are errors or if the chat is still loading, we will render a message, otherwise we will render the KendoReact Conversational UI component, passing the user object, the messages and the callback method to be run when the user sends a message. render src/ChatApp.js render() {if (this.state.error) {return <p>{this.state.error}</p>;} else if (this.state.isLoading) {return <p>Loading chat...</p>;}return (<ChatUIuser={this.user}messages={this.state.messages}onMessageSend={this.sendMessage}width={500}/>);} Lastly we need to render this entire component from the component. Import the component at the top of . <App> <ChatApp> src/App.js import React, { Component } from 'react';import Login from './Login';import ChatApp from './ChatApp';import '@progress/kendo-theme-material/dist/all.css'; Now update the function of the to return the component when the user is logged in. render <App> component <ChatApp> render() {let loginOrChat;if (this.state.loggedIn) {loginOrChat = <ChatApp username={this.state.username} />;} else {loginOrChat = (<LoginhandleLogin={this.handleLogin}handleUsernameChange={this.handleUsernameChange}username={this.state.username}/>);}return (<div className="container"><div className="row mt-3">{loginOrChat}</div></div>); Reload the app, login and start chatting. You can open another browser window and login with a different name to see the messages going back and forth. This is just the start is a powerful SDK for chatting and makes it really easy to display the chat in a React application. Most of the work we had to do was generating an access token and setting up the Twilio Chat. Once we’d written a couple of functions that translated the messages from Twilio to KendoReact and from KendoReact to Twilio the UI just fell into place. Twilio Programmable Chat KendoReact’s Conversational UI You can get all the code for this application in the . GitHub repo Check out the for other features of this UI, such as , useful when the other side is a bot, and , for ways to display media messages or other views, like lists or carousels, within your chat. KendoReact documentation suggested actions message attachments The KendoReact Conversational UI is also available for , and if you prefer a different framework, and there are plenty of other useful components you could use to build your application. jQuery Angular Vue Have you used KendoReact before? Or are you building chat into your app and on the lookout for a sweet UI? Let me know what you think in the comments or on . Twitter at @philnash Originally published at www.twilio.com .
Share Your Thoughts