Hands-On Tutorial: Integrating AI with React
Artificial Intelligence (AI) is no longer just for sci-fi movies and futuristic tech billionaires—it's here, and it can be part of your React app today! By integrating AI, you can add some serious wow factor, like chatbots, smart recommendations, and content generation. In this tutorial, we’ll build a simple AI-powered chatbot using OpenAI’s API, because let’s face it—who doesn’t want their app to talk back?
Prerequisites
Before we dive into the code like a caffeine-fueled developer on a hackathon weekend, make sure you have:
- Node.js installed
- A React project (or create one using Vite)
- An OpenAI API key (sign up at OpenAI)
Step 1: Create a React App with Vite
Forget the sluggishness of Create React App—Vite is here to turbocharge your development experience. And since we’re civilized developers, we’ll be using TypeScript instead of JavaScript—because type safety is cool. Set up your project with:
npm create vite@latest ai-chatbot --template react-ts
Then, navigate into your project and install dependencies:
cd ai-chatbot
npm install
npm run dev
Boom! You now have a blazing-fast development server.
Step 2: Install Axios
We need Axios to make HTTP requests, so let's install it:
npm install axios
No fluff, just action—like a well-typed TypeScript function.
Step 3: Set Up an API Utility
Now, let's create a simple utility to talk to OpenAI. Create openaiService.ts
inside the src
directory:
import axios from 'axios';
const API_KEY = 'your-openai-api-key';
const API_URL = 'https://api.openai.com/v1/chat/completions';
interface ChatMessage { role: 'user' | 'assistant'; content: string;}
export const getChatResponse = async (message: string): Promise<string> => {
try {
const response = await axios.post(
API_URL,
{
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message }],
},
{
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
return response.data.choices[0].message.content;
} catch (error)
{
console.error('Oops! Something went wrong:', error);
return 'Error processing request, but hey, at least I tried!';
}
};
Step 4: Create a Chat Component
Time to build our chatbot! Inside src/components
, create Chatbot.tsx
:
import React, { useState } from 'react';
import { getChatResponse } from '../openaiService';
interface ChatMessage { role: 'user' | 'assistant'; content: string;}
const Chatbot: React.FC = () => {
const [input, setInput] = useState<string>('');
const [messages, setMessages] = useState<ChatMessage[]>([]);
const handleSend = async () => {
if (!input.trim()) return;
const userMessage: ChatMessage = { role: 'user', content: input };
setMessages([...messages, userMessage]);
const response = await getChatResponse(input);
setMessages([...messages, userMessage, { role: 'assistant', content: response }]);
setInput('');
};
return (
<div>
<div>
{messages.map((msg, index) => (
<p key={index} style={{ color: msg.role === 'user' ? 'blue' : 'green' }}>
<strong>{msg.role}:</strong> {msg.content}
</p>
))}
</div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask me anything... (within reason, of course)"
/>
<button onClick={handleSend}>Send</button>
</div>
);
};
export default Chatbot;
Step 5: Integrate Chatbot in Main Component
Finally, let’s wire everything up in src/App.tsx
:
import React from 'react';
import Chatbot from './components/Chatbot';
const App: React.FC = () => {
return (
<div>
<h1>AI Chatbot</h1>
<Chatbot />
</div>
);
};
export default App;
Step 6: Run the App
It’s time for the grand reveal. Start your React app:
npm run dev
Congrats! Your AI chatbot is now alive and ready to answer (most of) your burning questions.
Final Thoughts
This is just the tip of the AI iceberg. You could integrate speech recognition, voice responses, or even make the chatbot more human-like (but, you know, not too human—let’s avoid Skynet scenarios).
Ready to level up? Try adding a fancy UI with react-chatbot-kit
or react-speech-kit
. The AI revolution is here—why not make it fun?
Looking for React Development & Consulting?
Karly and the team at Aviron Software specialize in custom software development, offering expertise in React Native mobile apps, React web applications, and .NET & ASP.NET Core. With a diverse client base spanning SaaS, healthcare, eCommerce, and management industries, Aviron Software delivers highly intuitive solutions designed to set your brand apart.
To discuss your project, email: hello@avironsoftware.com
or contact us.