Let’s create AI chatbot from scratch in Reactjs

Zeshanshakil
3 min readJul 30, 2023

--

Let’s create a full setup for the AI chatbot from scratch. We’ll use React for the frontend, Axios for making API requests, and some basic CSS for styling.

Please follow these steps:

  1. Create a new React app:
npx create-react-app ai-chatbot-app
cd ai-chatbot-app
  1. Install necessary dependencies:
npm install axios
  1. Get an API key:

Sign up for the OpenAI API and get your API key: https://beta.openai.com/signup/

  1. Create the Chatbot component:

Create a new file Chatbot.js in the src folder with the following content:

import React, { useState } from 'react';
import axios from 'axios';
import './Chatbot.css';

const Chatbot = () => {
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);

const chatWithGPT3 = async (userInput) => {
const apiEndpoint = 'https://api.openai.com/v1/engines/davinci-codex/completions';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer YOUR_OPENAI_API_KEY`
};

const data = {
prompt: userInput,
max_tokens: 150
};
try {
const response = await axios.post(apiEndpoint, data, { headers });
return response.data.choices[0].text.trim();
} catch (error) {
console.error('Error communicating with the API:', error.message);
return '';
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
const userMessage = { text: input, user: true };
setMessages((prevMessages) => [...prevMessages, userMessage]);
const aiMessage = { text: '...', user: false };
setMessages((prevMessages) => [...prevMessages, aiMessage]);
const response = await chatWithGPT3(input);
const newAiMessage = { text: response, user: false };
setMessages((prevMessages) => [...prevMessages.slice(0, -1), newAiMessage]);
setInput('');
};
return (
<div className="chatbot-container">
<div className="chatbot-messages">
{messages.map((message, index) => (
<div
key={index}
className={`message ${message.user ? 'user-message' : 'ai-message'}`}
>
{message.text}
</div>
))}
</div>
<form className="chatbot-input-form" onSubmit={handleSubmit}>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chatbot;
  1. Create the CSS file:

Create a new file Chatbot.css in the src folder with the following content:cssCopy code

/* Chatbot.css */

.chatbot-container {
width: 400px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
background-color: #f8f8f8;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.chatbot-messages {
height: 400px;
overflow-y: scroll;
padding: 8px;
}
.message {
margin: 8px 0;
padding: 8px;
border-radius: 4px;
font-size: 16px;
line-height: 1.5;
}
.user-message {
background-color: #007bff;
color: #fff;
text-align: right;
}
.ai-message {
background-color: #f0f0f0;
text-align: left;
}
.chatbot-input-form {
display: flex;
margin-top: 16px;
}
.chatbot-input-form input {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px 0 0 4px;
font-size: 16px;
}
.chatbot-input-form button {
padding: 8px 16px;
border: none;
background-color: #007bff;
color: #fff;
border-radius: 0 4px 4px 0;
font-size: 16px;
cursor: pointer;
}
.chatbot-input-form button:hover {
background-color: #0056b3;
}
  1. Use the Chatbot component in App.js:

Replace the content of src/App.js with the following code:

import React from 'react';
import Chatbot from './Chatbot';
/* App.js*/

function App() {
return (
<div>
<h1>AI Chatbot</h1>
<Chatbot />
</div>
);
}
export default App;
  1. Replace 'YOUR_OPENAI_API_KEY' in Chatbot.js:

Replace 'YOUR_OPENAI_API_KEY' in Chatbot.js with your actual API key obtained from Step 3.

  1. Start the development server:
npm start

Now, your React app with the AI chatbot is up and running! Visit http://localhost:3000 in your browser, and you should see the chatbot interface. Type your messages in the input box, and the AI's responses will appear in the chat area.

Remember to always handle API keys securely, especially if you plan to deploy this application. In a real-world scenario, consider using environment variables to store sensitive information like API keys.

--

--