Building a Chatbot with React and ChatGPT

Burak KILINC
turkcell
2 min readOct 13, 2023

--

Introduction

In this tutorial, we’ll walk through the process of creating a chatbot using React and OpenAI’s ChatGPT. ChatGPT is a powerful language model that can be used to build interactive and dynamic chatbots.

Prerequisites

  • Basic knowledge of React
  • Node.js and npm installed on your system
  • An OpenAI API key (sign up here if you haven’t already)

Step 1: Set Up Your React App

npx create-react-app chatbot-app
cd chatbot-app
npm start

Step 2: Install OpenAI Package

npm install openai

Step 3: Create a Chat Component

// src/Chat.js

import React, { useState } from 'react';
import { OpenAIAPIKey } from './config'; // Create a file named 'config.js' with your OpenAI API key

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

const sendMessage = async () => {
setMessages([...messages, { text: input, user: 'user' }]);
const response = await fetchMessage(input);
setMessages([...messages, { text: response, user: 'bot' }]);
setInput('');
};

const fetchMessage = async (input) => {
const response = await fetch('https://api.openai.com/v1/engines/davinci/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OpenAIAPIKey}`
},
body: JSON.stringify({
prompt: `You: ${input}\nAI:`,
max_tokens: 150
})
});
const data = await response.json();
return data.choices[0].text.trim();
};

return (
<div>
<div className="message-container">
{messages.map((message, index) => (
<div key={index} className={`message ${message.user}`}>
{message.text}
</div>
))}
</div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Type a message..."
/>
</div>
);
};

export default Chat;

Step 4: Configure OpenAI API

Create a config.js file in the src directory and add your OpenAI API key:

// src/config.js

export const OpenAIAPIKey = 'YOUR_API_KEY_HERE';

Step 5: Use the Chat Component

// src/App.js

import React from 'react';
import Chat from './Chat';

function App() {
return (
<div className="App">
<h1>ChatGPT Chatbot</h1>
<Chat />
</div>
);
}

export default App;

Step 6: Styling (Optional)

Feel free to add CSS to style your chat interface.

Conclusion

Congratulations! You’ve built a simple chatbot using React and ChatGPT. You can now further enhance and customize your chatbot based on your specific requirements.

Remember to handle errors and edge cases appropriately in a production environment. Happy coding!

--

--