How to make a Chatbot in React

For this week's blog post I decided to make a React chat bot.

The first thing I like to do is use create-react-app to setup my react "workspace" it sets up all the files I need and creates the directory. I like to make a corresponding github repository and initialize and add the github remote to the project.

Now that we have everything setup in our local environment and on github, we can get started.

I did a quick search and found this: https://lucasbassetti.com.br/react-simple-chatbot/#/docs/hello-world

It's a node package that helps you create a simple chatbot. Pretty cool. I installed it by typing

npm install react-simple-chatbot --save


I discovered that react simple chatbot used styled-components from https://www.styled-components.com/

It's an optional dependency and is recommended when you install react-simple-chatbot. 

Using styled-components will make it easier to modify the styling of the chatbot. 

I created a MainTheme component that will take care of passing in theme values to the ChatBot imported component. 

One thing to consider, if you import the ChatBot component and the page doesn't render, it's because it needs the steps array in order to work. 

The steps array is made up of hashes that contain an id, and then some other attributes such as whether it is a message to the user or to accept a message from the user. You can also specify a component to render, or to trigger another step by using trigger and giving it an id. This is how the chatbot makes decisions.

I separated out the steps array to make it easier to read all of the code. I did this by creating a new file called steps.js, then you just export the array.

I decided to use the custom component attribute to display links to github, linkedin and blog. It was relatively simple and to separate out each concern and make it easier to add more details, I put each one in it's own stateless component.





It's pretty basic in that it doesn't "say" much, but I just wanted to get a sense of how it works. I may add some new things to it in the future and I'm definitely open to feature requests.

If you want to see it in action, you can go here

Comments

Popular Posts