How to Build a Chatbot with Dialogflow and React Native

Chatbots provide a powerful way to integrate conversational experiences into software products. The quality of the user experience depends heavily on the chatbot's implementation. As Artificial Intelligence continues to advance, bots have become an increasingly integral part of the technology landscape.
This tutorial demonstrates how to build a chatbot application from scratch using Dialogflow and React Native. Dialogflow, a service from Google, is chosen for its accessibility, as it does not require a complex sign-up process involving credit card details, unlike many other bot frameworks.
The goal is to build a simple chatbot capable of understanding different ways a user might ask for the current date and responding accordingly.
The complete code for this tutorial can be found in this Github repository.
Requirements
To follow this tutorial, you will need:
react-native-cli(version2.0.1or above), available vianpm.- A solid understanding of React, React Native, and JavaScript.
- A Google account.
react-native-gifted-chatfor the chat UI.react-native-dialogflowto connect the app with Dialogflow's SDK.
Getting Started
First, initialize a new React Native project using react-native-cli.
react-native init RNDiagflowChatbot
cd RNDiagflowChatbot
Next, install the required dependencies. react-native-dialogflow has a peer dependency on react-native-voice, so it must be installed as well, even though we will not use it directly.
npm install --save react-native-gifted-chat react-native-dialogflow react-native-voice
Link the native dependencies for both libraries:
react-native link react-native-dialogflow
react-native link react-native-voice
To prevent the application from crashing on iOS, you must add microphone and speech recognition permissions to the ios/RNDiagflowChatbot/Info.plist file inside the root <dict> tag.
<!-- Info.plist -->
<key>NSSpeechRecognitionUsageDescription</key>
<string>Your usage description here</string>
<key>NSMicrophoneUsageDescription</key>
<string>Your usage description here</string>
Now, let's create the initial chat component in App.js. We will use the GiftedChat component to quickly build a feature-rich chat interface.
// App.js
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
class App extends Component {
state = {
messages: [
{
_id: 1,
text: `Hi! I am the FAQ bot from Jscrambler.\n\nHow may I help you today?`,
createdAt: new Date(),
user: {
_id: 2,
name: 'FAQ Bot',
avatar: 'https://i.imgur.com/7k12EPD.png'
}
}
]
};
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages)
}));
}
render() {
return (
<View style={{ flex: 1, backgroundColor: '#fff' }}>
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1
}}
/>
</View>
);
}
}
export default App;
The component is initialized with a static welcome message. The GiftedChat component takes the messages array from the state, an onSend callback to handle new messages, and a user object representing the current user.
Run the app in your simulator (react-native run-ios or react-native run-android) to see the initial chat interface.

Google's Dialogflow Setup
Dialogflow is a Natural Language Processing (NLP) service from Google. Visit the Dialogflow website and create a new account or log in. Once logged in, create a new Agent. An agent understands the nuances of human language and translates it into structured data your application can use.

A conversation with a Dialogflow agent involves the user providing input, the agent parsing that input, and the agent returning a response. Each agent contains one or more Intents.
Creating the First Intent
An intent represents an action or response triggered by user input. Let's create an intent named date.current. Its purpose is to return the current date when asked.
Add several Training phrases that a user might use to ask for the date, such as "What is the date today?" or "Show me the current date".

Dialogflow automatically recognizes "date" as a parameter. Finally, add a text Response for the agent to send back to the user.

Save the intent.
Connecting Dialogflow with React Native
To connect your app, you need service account credentials from your Dialogflow agent. Go to your agent's Settings (gear icon), and in the General tab, click the link next to Service Account.
This will take you to the Google Cloud Platform console. Find the service account named Dialogflow Integrations, click the three-dots menu, and select Create Key. Choose JSON as the key type and download the file.
The downloaded JSON file will contain your project's credentials, including a private key.
Building the Chatbot
Create a new file named env.js in your project's root and copy the contents of the downloaded JSON file into a dialogflowConfig object.
// env.js
export const dialogflowConfig = {
"type": "service_account",
"project_id": "YOUR_PROJECT_ID",
"private_key_id": "YOUR_PRIVATE_KEY_ID",
"private_key": "YOUR_PRIVATE_KEY",
"client_email": "YOUR_CLIENT_EMAIL",
"client_id": "YOUR_CLIENT_ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "YOUR_CLIENT_X509_CERT_URL"
};
Important: Replace the placeholder values with your actual credentials. Never commit this file to public version control.
Now, update App.js to use these credentials. Import the Dialogflow library and your configuration.
import { Dialogflow_V2 } from 'react-native-dialogflow';
import { dialogflowConfig } from './env';
Refactor the user object out of the state for better organization.
const BOT_USER = {
_id: 2,
name: 'FAQ Bot',
avatar: 'https://i.imgur.com/7k12EPD.png'
};
In componentDidMount, configure the Dialogflow SDK with your credentials.
componentDidMount() {
Dialogflow_V2.setConfiguration(
dialogflowConfig.client_email,
dialogflowConfig.private_key,
Dialogflow_V2.LANG_ENGLISH_US,
dialogflowConfig.project_id
);
}
Next, modify the onSend method to send the user's message to Dialogflow using Dialogflow_V2.requestQuery. This method takes the message text and two callbacks: one for a successful result and one for an error.
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages)
}));
let message = messages[0].text;
Dialogflow_V2.requestQuery(
message,
result => this.handleGoogleResponse(result),
error => console.log(error)
);
}
The handleGoogleResponse function processes the result from Dialogflow and sends the bot's reply back to the chat UI.
handleGoogleResponse(result) {
let text = result.queryResult.fulfillmentMessages[0].text.text[0];
this.sendBotResponse(text);
}
sendBotResponse(text) {
let msg = {
_id: this.state.messages.length + 1,
text,
createdAt: new Date(),
user: BOT_USER
};
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, [msg])
}));
}
The sendBotResponse function updates the component's state, causing GiftedChat to render the new message from the bot.
Here is the final application in action:

Conclusion
Integrating a powerful NLP service like Dialogflow into a React Native application is straightforward. With libraries like react-native-gifted-chat and react-native-dialogflow, you can quickly build a functional chatbot interface to serve as a valuable support or marketing tool for your product.