Build a chat app with Twilio and KendoReact
Time to read: 8 minutes
Twilio Programmable Chat 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 KendoReact might be what you're looking for.
Kendo UI provides well designed and tested components that you can use within your React, Angular, Vue and jQuery applications. In this post we will build a Twilio Chat application with React and the KendoReact conversational UI components.
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 Twilio Chat service and an API key and secret, both of which you can create in the Twilio console (keep these nearby, you'll need them soon)
- Node.js 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)
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 React and Express starter application that I built in this post 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. Download or clone the application, change into the directory, and install the dependencies:
Copy the .env.example
file to .env
then fill in the blanks with your Twilio account SID, the chat service, and API keys you generated earlier.
Run the application to make sure everything is working so far. On the command line run:
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 twilio-chat
module to connect with Twilio Chat and then a few KendoReact modules that will provide the components we're going to use:
Next, strip src/App.js
back to the basics, including the CSS for the KendoReact Material theme:
To give the application a bit more style and layout (without too much effort) add the Bootstrap CSS to the <head>
of public/index.html
:
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, src/Login.js
, and open it up. We'll make this a functional component as the login form itself doesn't need to store any state. Start with the following boilerplate:
To make our Login form fit in with our conversational UI, we'll use KendoReact components. At the top import the Button
and Input
components:
Modify the Login
function to return the following JSX:
That's quite the chunk of JSX, so let's break it down. The whole thing is a <form>
containing a <fieldset>
and <legend>
. Then inside there is an <Input>
component and a <Button>
component. These are the KendoReact components that we imported. They act like regular <input>
and <button>
elements but fit in with the KendoReact style.
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 <App>
component so we can pass them in as properties.
Open up src/App.js
and start by importing the new <Login>
component.
Define the two functions that we'll be passing to the <Login>
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 <App>
component's constructor in src/App.js
:
In the constructor we need to initialise the state and bind these functions to the component:
Now let's update the render
function to show the username if the state says the user is logged in, and the <Login>
component otherwise.
If your application is still running, return to the browser and you will see the login form. Otherwise start the app with npm run dev
and open localhost:3000
. Enter your name in the form and press enter or click "Sign in".
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 src/ChatApp.js
and open it up. We'll create a class based component for the chat app, so add the following boilerplate:
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 src/ChatApp.js
add:
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
.
Getting an access token
The starter project is already setup to return a token when we pass an identity to the /chat/token
endpoint. We'll use the fetch
API to make the request as part of the componentDidMount
lifecycle event. We use componentDidMount
here as the React documentation tells us that this is a good place to load external data.
The response with the access token will be JSON, so we'll need to parse it using the response object's json
method then once it's parsed, we can use the token to initialise the Chat client.
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 catch
method.
Add this code to the ChatApp
class below the constructor:
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.
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 setupChatClient
method to the class:
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 isLoading
variable to false
. We also need to load existing messages and set up a listener for new messages.
Replace the // Success!
comment above with:
Receiving Messages
We need to write the messagesLoaded
and messageAdded
methods we just referenced above, but before we do we need to consider the format that the KendoReact conversational UI wants the messages. We need to translate the message object from the format Twilio provides it to that which can be used by the conversational UI component.
Let's write a function that can take a message from the Chat service and return a message object for KendoReact:
Now we can write the messagesLoaded
and messageAdded
methods. messagesLoaded
runs when we first load the existing messages to a channel so we fill up state.messages
with all the messages we receive.
messageAdded
will receive one message as its argument so we use the callback version of setState
to add the message to the list. Note we also use the spread operator (...
) to copy the existing messages into the new state.
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 messageAdded
event we are listening to on the channel.
Add the following function to the ChatApp
class:
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.
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:
Rendering the chat
Now we have everything in place we can render the Conversational UI. Create a render
method in src/ChatApp.js
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.
Lastly we need to render this entire component from the <App>
component. Import the <ChatApp>
component at the top of src/App.js
.
Now update the render
function of the <App> component
to return the <ChatApp>
component when the user is logged in.
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
Twilio Programmable Chat is a powerful SDK for chatting and KendoReact's Conversational UI 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.
You can get all the code for this application in the GitHub repo.
Check out the KendoReact documentation for other features of this UI, such as suggested actions, useful when the other side is a bot, and message attachments, for ways to display media messages or other views, like lists or carousels, within your chat.
The KendoReact Conversational UI is also available for jQuery, Angular and Vue if you prefer a different framework, and there are plenty of other useful components you could use to build your application.
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.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.