Build a React Chatbot Component
Last Modified: Oct. 19, 2020, 9:51 a.m.
Today we will build a React chatbot app that collects contact information.
If you are new to React, check out the React Tutorial for Beginners.
What is required to create this React Chatbot?
- install Node.js and npm
- install and configure create-react-app
- install and configure react-simple-chatbot
- install styled-components
We will be walking through each of these packages, including their installation and application.
If you are looking for a pre-built React Chatbot, download the project React Chatbot.
Node.js and npm
Node.js and npm install together using the Node installer.
Check Node.js and npm installations
Check version number - Windows Command Prompt
C:\Users\Owner>node -v
v12.13.1
C:\Users\Owner>npm -v
6.12.1
Check version number - macOS Terminal
User-Macbook:~ user$ node -v
v12.13.1
User-Macbook:~ user$ npm -v
6.12.1
Run node -v
and npm -v
in your command prompt. If no version number appears, you need to install Node.
Create a React App with Facebook create-react-app
The create-react-app by Facebook handles the basic React app configurations while also reporting errors in the code.

We’ll install create-react-app
via the command prompt.
Create your app with create-react-app
create-react-app - Windows Command Prompt
C:\Users\Owner\desktop\react> npx create-react-app react-chatbot
create-react-app - macOS Terminal
User-Macbook:react user$ npx create-react-app react-chatbot
Run npx create-react-app react-chatbot
to create a React app named react-chatbot.
Run the React App development server
Run app - Windows Command Prompt
C:\Users\Owner\desktop\react> cd react-chatbot
C:\Users\Owner\desktop\react\react-chatbot> npm start
Run app - macOS Terminal
User-Macbook:react user$ cd react-chatbot
User-Macbook:react-chatbot user$ npm start
cd
into the project with the command cd react-chatbot
.
Then run the command npm start
to open your React app in the browser.

Edit the create-react-app files
Delete all of the files in the src directory except the index.js and App.js files. We do not want to keep any necessary code for this project.
We will be covering index.js and App.js quickly, so if you are looking for an in-depth description checkout the React Tutorial for Beginners.
Connect index.js to your React App
react-chatbot > src > index.js (updated)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'))
Delete the existing code in index.js and update the file with the code above.
index.js uses the ReactDOM.render()
function to render the React component <App />
where id="root"
is called in the index.html.
Add a class component to App.js
react-chatbot > src > App.js (updated)
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div className="App">
<h1>Some Text</h1>
</div>
);
}
}
export default App;
Next, go to App.js. Replace the existing App
class component with the one seen above.
Have the class component render some JSX code.
We just want to make sure our App.js, index.js, and index.html are all connected properly.
Then look at your app in the browser at http://lcoalhost:3000/, you may need to reload the page, and you'll see the JSX code rendered as HTML.

Now it's time to build the chatbot components.
Organizing React files
To stay organized, let's create two new directories and a new file for our chatbot.
Create a SimpleForm.js file
react-chatbot > src > (New Folder) components > (New Folder) chatbot > (New File) SimpleForm.js
import React, { Component } from 'react';
class SimpleForm extends Component {
render() {
return (
<div>
</div>
);
}
}
export default SimpleForm;
Create a new folder called components in the src directory. This directory holds your custom components.
Next, create a folder called chatbot in the components directory. All React chatbot code goes in components > chatbot directory.
Finally, create a file called SimpleForm.js in the chatbot directory for the React chatbot component.
The file structure is src > components > chatbot > SimpleForm.js.
Add import React, { Component } from 'react'
to the top of the file. Then add a class component called SimpleForm
and a render()
method with a return()
.
Add an empty division element to the return()
for now to avoid parsing errors.
Export SimpleForm
at the bottom of the file before moving on to the next step.
Import SimpleForm in App.js
react-example > src > App.js (updated)
import React, { Component } from 'react';
import SimpleForm from "./components/chatbot/SimpleForm";
class App extends Component {
render() {
return (
<div>
<SimpleForm />
</div>
);
}
}
export default App;
Update the App.js to import SimpleForm
from the components > chatbot > SimpleForm.js file.
Then update the render()
method to return the <SimpleForm />
component.
Now, anything added to the SimpleForm
component renders in the App
component.
The App
component then exports to index.js and the ReactDOM.render()
function renders the code in index.html.
Before we can add the React chatbot code, we need to install react-simple-chatbot
.
React Simple Chatbot
React Simple Chatbot is a chatbot component used to create conversation chats. Created by Lucas Bassetti, it is a fast way to get a custom, mobile-friendly chatbot on any website.
Install react-simple-chatbot
Install react-simple-chatbot - Windows Command Prompt
(Ctrl + C)
Terminate batch job (Y/N)? y
C:\Users\Owner\desktop\react\react-chatbot>npm install react-simple-chatbot --save
...
Install react-simple-chatbot - macOS Terminal
(command + C)
Terminate batch job (Y/N)? y
User-Macbook:react-chatbot user$ npm install react-simple-chatbot --save
...
Terminate the batch and install react-simple-chatbot
with npm.
Install styled-components
Install style-components- Windows Command Prompt
C:\Users\Owner\desktop\react\react-chatbot>npm install styled-components
...
C:\Users\Owner\desktop\react\react-chatbot>npm start
Install styled-components - macOS Terminal
User-Macbook:react-chatbot user$ npm install styled-components
...
C:\Users\Owner\desktop\react\react-chatbot>npm start
Also install styled-components
, a package that will allow us to change the theme of the chatbot.
Run npm start
after the installations.
Import react-simple-chatbot in SimpleForm.js
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot />
);
}
}
export default SimpleForm;
Go to SimpleForm.js and import ChatBot from 'react-simple-chatbot'
at the top of the file.
Then call the <ChatBot />
component within the return.
Add text steps to the ChatBot component
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'intro',
message:'Hello world. I am a chatbot.',
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
The ChatBot
class component uses the property steps
to list an array of text, user, and option steps.
You will get the TypeError: Cannot read property 'length' of undefined
if you do not add steps to the component.
We will start with the text steps. These are the steps that the Chatbot states to the user.
Common Text Step Attributes:
id
(string or number) - required for any step
message
(string or function) - a message to the user
trigger
(string, number, or function) - the id of the next step triggered
delay
(number) - the delay time before the message appears
end
(boolean) - if true, this step is the end of the conversation
The example above only has one step that tells the user "Hello world. I am a chatbot."
If you look in the browser window, you'll see the chatbot and the text appear.

Add user steps to the ChatBot component
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'intro',
message:'Hello. What is your name?',
trigger:'intro-user',
},
{
id:'intro-user',
user:true,
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
User steps are steps that require a typed user response.
Common User Step Attributes:
id
(string or number) - required for any step
user
(boolean) - if true, this step waits for a user type action
validator
(function) - a function used to validate the typed user text
trigger
(string, number, or function) - the id of the next step triggered
end
(boolean) - if true, this step is the end of the conversation
The example above has two steps.
First, the chatbot says "Hello. What is your name?", "Type the message..." accepts a user input that then appears in the chat conversation after the user clicks Enter.

Add option steps to the ChatBot component
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'intro',
message:'Do you agree to the Terms and Conditions?',
trigger:'intro-user',
},
{
id:'intro-user',
options:[
{value:'y', label:'Yes', trigger:'yes-response'},
{value:'n', label:'No', trigger:'no-response'},
]
},
{
id:'yes-response',
message:'Great!',
end:true,
},
{
id:'no-response',
message:'Sorry to hear that.',
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
Option steps provide the user with a list of options rather than requesting an input.
Common Option Step Attributes:
id
(string or number) - required for any step
options
(array) - options with {value, label, trigger}
properties
end
(boolean) - if true, this step is the end of the conversation
The example above has three steps, with the final step depending on the option selected by the user.
First, the chatbot says "Do you agree to the Terms and Conditions?" then the user is presented with the option "Yes" or "No". The chatbot replies "Great!" if the user selects "Yes" and "Sorry to hear that." if the user selects "No".

React Simple Chatbot User step with validation
Validation is an option for user steps that have the user:true
attribute value. We suggest adding a validator where ever possible to minimize user error and prevent bad data posting into the system.

Below are some common validators.
Name validator
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'q-name',
message:'Hello. What is your name?',
trigger:'name',
},
{
id:'name',
user:true,
validator: (value) => {
if (/^[A-Za-z][A-Za-z\'\-]+([\ A-Za-z][A-Za-z\'\-]+)*/.test(value))
{
return true;
}
else
{
return'Please input alphabet characters only.';
}
},
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
Above is a validator function using REGEX to validate a two or more word name with hyphen and apostrophe support.
If underscores or numbers are entered, an error message will appear requesting on alphabet characters.
To validate one-word names, use the REGEX /^[A-Za-z]+/
instead.
Email validator
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'q-email',
message:'Hello. What is your email?',
trigger:'email',
},
{
id:'email',
user:true,
validator: (value) => {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
return true;
}
else
{
return'Please enter a valid email.';
}
},
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
The email validation function looks for an @ symbol, email domain, and a period followed by the 2-3 ending of a domain name (i.e. "com", "edu", "net").
Zip code validator
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'q-zip',
message:'Hello. What is your email?',
trigger:'zip',
},
{
id:'zip',
user:true,
validator: (value) => {
if (/^[0-9]{5}(?:-[0-9]{4})?$/.test(value))
{
return true;
}
else
{
return'Please enter a valid zip code.';
}
},
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
The zip code validation function accepts U.S. zip codes with either a five-digit or nine-digit zip code, with our without a dash.
Phone number validator
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'q-phone',
message:'Hello. What is your phone number?',
trigger:'phone',
},
{
id:'phone',
user:true,
validator: (value) => {
if (/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(value))
{
return true;
}
else
{
return'Please enter a valid phone number.';
}
},
end:true,
},
]}
/>
);
}
}
export default SimpleForm;
Valid phone numbers are 10 digit U.S. numbers and can include parentheses or dashes.
React Simple Chatbot with Custom Theme
React Simple Chatbot also allows for custom theming.
Import ThemeProvider property in SimpleForm.js
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
import { ThemeProvider } from 'styled-components';
// all available theme props
const theme = {
background: '#f5f8fb',
fontFamily: 'Helvetica Neue',
headerBgColor: '#EF6C00',
headerFontColor: '#fff',
headerFontSize: '15px',
botBubbleColor: '#EF6C00',
botFontColor: '#fff',
userBubbleColor: '#fff',
userFontColor: '#4a4a4a',
};
class SimpleForm extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<ChatBot
steps={[
{
id:'intro',
message:'Do you agree to the Terms and Conditions?',
trigger:'intro-user',
},
{
id:'intro-user',
options:[
{value:'y', label:'Yes', trigger:'yes-response'},
{value:'n', label:'No', trigger:'no-response'},
]
},
{
id:'yes-response',
message:'Great!',
end:true,
},
{
id:'no-response',
message:'Sorry to hear that.',
end:true,
},
]}
/>
</ThemeProvider>
);
}
}
export default SimpleForm;
Import { ThemeProvider }
as a property of styled-components
at the top of the file. Then add the ES6 variable const
.
ES6, or ECMAScript 6, standardizes JavaScript and allows us to define variables using var
, let
, and const
.
We'll use const
to define the theme
prop. The variable const is used because the value of the variable will not change.
Next, nest the SimpleForm component within the <ThemeProvider> </ThemeProvider>
wrapper component and call theme as a property within the opening tag of the wrapper component.

Add config properties to the React Simple Chatbot
The config prop allows for further customization of the chatbot.
Resize the React Simple Chatbot
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
// all available config props
const config ={
width: "400px",
height: "500px",
};
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'intro',
message:'Do you agree to the Terms and Conditions?',
trigger:'intro-user',
},
{
id:'intro-user',
options:[
{value:'y', label:'Yes', trigger:'yes-response'},
{value:'n', label:'No', trigger:'no-response'},
]
},
{
id:'yes-response',
message:'Great!',
end:true,
},
{
id:'no-response',
message:'Sorry to hear that.',
end:true,
},
]}
{...config}
/>
);
}
}
export default SimpleForm;
Add a const variable at the top of the page with a config property. Specify the width and height. Then add the {... config}
props right after the steps props.
Render the React Simple Chatbot with a floating button
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
// all available config props
const config ={
width: "400px",
height: "500px",
floating: true,
};
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'intro',
message:'Do you agree to the Terms and Conditions?',
trigger:'intro-user',
},
{
id:'intro-user',
options:[
{value:'y', label:'Yes', trigger:'yes-response'},
{value:'n', label:'No', trigger:'no-response'},
]
},
{
id:'yes-response',
message:'Great!',
end:true,
},
{
id:'no-response',
message:'Sorry to hear that.',
end:true,
},
]}
{...config}
/>
);
}
}
export default SimpleForm;
To make the chatbot a floating button on the page load, add the property floating
(boolean) to config
. To see the other properties, check out the API reference Chatbot properties.

Posting the Simple React Form
To post the information collected from your React Chatbot, you will need a new class component called Post
that uses a constructor()
method with properties and state objects, a componetDidMount()
method with state objects and axios, followed by a render()
method with a return.
Create a new file called Post.js
react-chatbot > src > components > chatbot > (New File) Post.js
import React, { Component } from 'react';
class Post extends Component {
constructor() {
}
componentDidMount() {
}
render() {
}
};
export default Post;
Create a new file called Post.js in src > components > chatbot. Then add a constructor()
method.
A constructor method initializes an object created in a class component. There can only be one in each class component.
Next, add a componentDidMount()
method. This is where we'll load in the data and instantiate the network request to post the data.
Finally, add a render()
method that will display a message to the user.
We will be filling out these methods in a little bit.
Export Post
at the bottom of the page so we can import it in SimpleForm.js.
Import Post in SimpleForm.js
react-chatbot > src > components > chatbot > SimpleForm.js
import React, { Component } from 'react';
import ChatBot from 'react-simple-chatbot';
import Post from './Post';
class SimpleForm extends Component {
render() {
return (
<ChatBot
steps={[
{
id:'q-firstname',
message:'What is your first name?',
trigger:'firstname',
},
{
id:'firstname',
user:true,
trigger:'q-lastname'
},
{
id:'q-lastname',
message:'What is your last name?',
trigger:'lastname',
},
{
id:'lastname',
user:true,
trigger:'q-email'
},
{
id:'q-email',
message:'Finally. what is you email?',
trigger:'email',
},
{
id:'email',
user:true,
trigger:'q-submit'
},
{
id:'q-submit',
message:'Do you wish to submit?',
trigger:'submit'
},
{
id:'submit',
options:[
{value:'y', label:'Yes', trigger:'end-message'},
{value:'n', label:'No', trigger:'no-submit'},
]
},
{
id: 'no-submit',
message:'Your information was not submitted.',
end: true,
},
{
id: 'end-message',
component: <Post />,
asMessage: true,
end: true,
},
]}
/>
);
}
}
export default SimpleForm;
Then let's import Post
into SimpleForm.js.
Create new steps and add an end step that calls on the <Post />
component and displays it as a chatbot message.
The steps in this chatbot ask for first name, last name, email address, and if they would like to submit their information.
The browser and command prompt will present the error Your render method should have return statement
, but before we can add the posting code, we'll install Axios top perform a POST
request.
Axios
Axios makes HTTP requests to fetch or save data from a client-side JavaScript application. It is a promise-based HTTP client that works within a Node.js environment.
Install react-simple-chatbot
Install axios - Windows Command Prompt
Failed to compile.
./src/components/chatbot/Post.js
Line 14:3: Your render method should have return statement react/require-render-return
Search for the keywords to learn more about each error.
(Ctrl + C)
Terminate batch job (Y/N)? y
C:\Users\Owner\desktop\react\react-chatbot>npm install axios
...
C:\Users\Owner\desktop\react\react-chatbot>npm start
Install axios - macOS Terminal
Failed to compile.
./src/components/chatbot/Post.js
Line 14:3: Your render method should have return statement react/require-render-return
Search for the keywords to learn more about each error.
(command + C)
Terminate batch job (Y/N)? y
User-Macbook:react-chatbot user$ npm install axios
...
User-Macbook:react-chatbot user$ npm start
Terminate the batch and install axios
with npm. Then you can run npm start
.
We are about to handle the Your render method should have return statement
. Don't worry.
Update the constructor() method to the Post class component
react-chatbot > src > components > chatbot > Post.js
import React, { Component } from 'react';
class Post extends Component {
constructor(props) {
super(props);
const { steps } = this.props;
const { submit, firstname, lastname, email } = steps;
this.state = { submit, firstname, lastname, email };
}
componentDidMount() {
}
render() {
}
};
export default Post;
Within the constructor method:
- Call
super(props)
to define props
- Assign the steps property as a
const
variable equal to this.props
- Assign the
submit
, firstname
, lastname
, and email
user steps equal to the variable steps
- Finally, assign the initial state,
this.state
, as each user step
This is how we'll get the user input values from the steps property.
Update the componentDidMount() method to the Post class component
react-chatbot > src > components > chatbot > Post.js
import React, { Component } from 'react';
import axios from 'axios';
class Post extends Component {
constructor(props) {
super(props);
const { steps } = this.props;
const { submit, firstname, lastname, email } = steps;
this.state = { submit, firstname, lastname, email };
}
componentDidMount() {
const userObject = {
submit:this.state.submit.value,
first_name:this.state.firstname.value,
last_name:this.state.lastname.value,
email:this.state.email.value,
};
axios.post(`/api`, userObject)
.then(res => {
console.log(res.status)
}).catch(function(error) {
console.log(error);
});
}
render() {
}
};
export default Post;
Next, import axios
at the top of the file.
Then, set the const
variable userObject
equal to a dictionary. The dictionary will have unique keys followed by this.state.step_id.value
for each of the user input values.
Call the axios aliases for a post request immediately after the const variable. The format is axios.post( 'URL', data)
.
Add .then()
and .catch()
to print out the errors in the console, however, these are not required to execute the request.
The data sent is formatted as a JSON string.
Update the return() method to the Post class component
react-chatbot > src > components > chatbot > Post.js
import React, { Component } from 'react';
import axios from 'axios';
class Post extends Component {
constructor(props) {
super(props);
const { steps } = this.props;
const { submit, firstname, lastname, email } = steps;
this.state = { submit, firstname, lastname, email };
}
componentDidMount() {
const userObject = {
submit:this.state.submit.value,
first_name:this.state.firstname.value,
last_name:this.state.lastname.value,
email:this.state.email.value,
};
axios.post(`/api`, userObject)
.then(res => {
console.log(res.status)
}).catch(function(error) {
console.log(error);
});
}
render() {
return (
<div>Thank you! Your data was submitted successfully!</div>
);
}
};
export default Post;
The last thing to update is the render()
method. The only thing that needs to be added here is a JSX element that let's the user know their information is posted.
See if the data is posting
Return back to your browser window and open your developer tools.
For Chrome, right-click on the page > Inspect > Console.
Respond to each chatbot question. When you click "Yes" on the final question, you should get a 404 error because we did not enter in an actual URL for Axios to post to, only a slug called /api
.
Click on the URL http://localhost:3000/api
and it will open the "Network" tab. Click on api
and scroll to the bottom of the "Headers" window where you should see the "Request Payload" with the JSON information submitted.

Common React errors and their solutions
ERROR
: No such file or directory; This is related to npm not being able to find a file.
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\Owner\Desktop\react\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Owner\Desktop\react\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Owner\AppData\Roaming\npm-cache\_logs\2020-10-16T18_58_34_986Z-debug.log
This error occurs if you forget to cd
into your app folder before running npm start
.
ERROR: 'SimpleForm' is not defined
./src/App.js
Line 8:10: 'SimpleForm' is not defined react/jsx-no-undef
Search for the keywords to learn more about each error.
This means you forgot to import SimpleForm at the top of App.js.
ERROR: Module not found: Can't resolve 'styled-components'
./node_modules/react-simple-chatbot/dist/react-simple-chatbot.js
Module not found: Can't resolve 'styled-components'
You forgot to install styled-components. You will get a similar module error if you forget to install axios or any other package used.
ERROR: The id does not exist
Error: The id 'firstname' triggered by step 'q-firstname' does not exist
If you are getting something similar to this error, it means that there is no step with the id 'firstname'
. Make sure all triggers call the exact id used by a step.
ERROR: Parsing error: Unexpected token
Failed to compile.
./src/components/chatbot/SimpleForm.js
Line 7:5: Parsing error: Unexpected token
5 | return (
6 |
> 7 | );
| ^
8 | }
9 |
10 | }
This error occurs if you leave the return() empty.
ERROR:TypeError: Cannot read property 'length' of undefined
If you do not add any steps to the ChatBot component, this error occurs.
Pre-built React Chatbot Component
If you are interested in a completed version of this chatbot, visit the React Chatbot under the "Projects" tab.
