
Build an AI Chatbot in React Using OpenAI GPT API enables you to create an interactive chatbot that can answer customer queries directly on your website. This guide provides a step-by-step approach to building a fully functional chatbot using React and the OpenAI GPT API.
Table of content:
1. Introduction
In this guide, we’ll build a fully functional AI chatbot using React and the OpenAI GPT API, allowing users to ask questions and get human-like responses — perfect for customer support or engagement on your website.
2. Prerequisites
Before starting, ensure you have the following:
- 1. Basic knowledge of React and JavaScript/TypeScript
- 2. Node.js and npm installed
- 3. An OpenAI API key (get it from OpenAI Dashboard)
Step 1: Set Up Your React Project
Create a new React project using Create React App in terimal of your project folder:
npx create-react-app ai-chatbot
cd ai-chatbot
npm install axios
Open your vs code in ai-chatbot folder
Step 2: Create the Chat UI
1. Create a file Chatbot.jsx inside the src folder:
import React, { useState } from "react";
import axios from "axios";
const Chatbot = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const sendMessage = async (e) => {
e.preventDefault();
if (!input.trim()) return;
const newMessage = { sender: "user", text: input };
setMessages([...messages, newMessage]);
setInput("");
setLoading(true);
try {
const res = await axios.post("http://localhost:5000/api/chat", { prompt: input });
setMessages((prev) => [...prev, { sender: "bot", text: res.data.response }]);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
return (
<div style={styles.container}>
<div style={styles.chatBox}>
{messages.map((msg, i) => (
<div key={i} style={{ ...styles.message, alignSelf: msg.sender === "user" ? "flex-end" : "flex-start", backgroundColor: msg.sender === "user" ? "#007bff" : "#e5e5ea", color: msg.sender === "user" ? "#fff" : "#000" }}>
{msg.text}
</div>
))}
{loading && <p>🤖 Typing...</p>}
</div>
<form onSubmit={sendMessage} style={styles.inputBox}>
<input style={styles.input} value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask me anything..." />
<button type="submit" style={styles.button}>Send</button>
</form>
</div>
);
};
const styles = {
container: {
width: "400px",
margin: "50px auto",
display: "flex",
flexDirection: "column",
border: "1px solid #ccc",
borderRadius: "10px",
padding: "10px",
backgroundColor: "#fff",
boxShadow: "0 4px 8px rgba(0,0,0,0.1)",
fontFamily: "Arial, sans-serif",
},
chatBox: {
flex: 1,
display: "flex",
flexDirection: "column",
overflowY: "auto",
height: "400px",
padding: "10px",
gap: "10px",
marginBottom: "10px",
border: "1px solid #e5e5ea",
borderRadius: "10px",
backgroundColor: "#f9f9f9",
},
message: {
padding: "10px 15px",
borderRadius: "15px",
maxWidth: "70%",
wordBreak: "break-word",
},
inputBox: {
display: "flex",
gap: "10px",
},
input: {
flex: 1,
padding: "10px",
borderRadius: "5px",
border: "1px solid #ccc",
outline: "none",
fontSize: "14px",
},
button: {
padding: "10px 15px",
backgroundColor: "#007bff",
color: "#fff",
border: "none",
borderRadius: "5px",
cursor: "pointer",
fontWeight: "bold",
},
};
export default Chatbot;
2. Then import it in App.jsx:
import React from "react";
import Chatbot from "./Chatbot";
function App() {
return (
<div>
<h1 style={{ textAlign: "center" }}>AI Chatbot 🤖</h1>
<Chatbot />
</div>
);
}
export default App;
Step 3: Create the Backend with Express
1. Run the following commands:
mkdir server
cd server
npm init -y
npm install express cors axios dotenv openai
2. Open your vs code in server folder
3. Create index.js:
const express= require("express")
const cors= require("cors")
const dotenv= require("dotenv")
const {OpenAI}= require("openai")
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
app.post("/api/chat", async (req, res) => {
try {
const prompt = req.body.prompt;
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
});
res.json({ response: response.choices[0].message.content });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Something went wrong" });
}
});
app.listen(5000, () => console.log("Server running on http://localhost:5000"));
4. Create a .env file in server folder:
Quick guide how to get open ai api key: How to Get an OpenAI API Key (Quick Guide)
OPENAI_API_KEY=your_openai_api_key_here
5. Run the server:
node index.js
Step 4: Connect Frontend and Backend
Your React app sends requests to http://localhost:5000/api/chat, and the backend handles them using OpenAI’s API. Ensure both servers are running:
- Frontend: npm start
- Backend: node index.js
Step 5: Test the Chatbot
Open http://localhost:3000 and try questions like:
- Q1. "What is React?"
- Q2. "Tell me a joke."
- Q3. "Write a 1-line motivational quote."
3. Conclusion and Next Steps
You’ve successfully built an AI-powered chatbot in React using the OpenAI GPT API. This chatbot can be customized for customer support, product recommendations, knowledge base Q&A, or personal assistant apps.
Next steps you can take:
- 1. Add chat memory to remember previous messages.
- 2. Integrate authentication for user-specific chats.
- 3. Use React Native or Next.js to expand to mobile or web apps.