React + TypeScript + ChatGPT

Andres Zenteno
The Tech Pulse
Published in
3 min readMar 12, 2023
Photo by Levart_Photographer on Unsplash

There are many articles around telling you how to integrate ChatGPT with a React project. But because I couldn’t find an example of how to do it on a React+Typescript project then I created mine.

First, you will need to get an OpenAI API Key. To achieve that you have to go to https://platform.openai.com/account/api-keys and create a new secret key.

To create the React+TypeScript project I decided to use ViteJS (or just Vite), I found it pretty easy to use. But that’s up to you, you can create your React+TypeScript project the regular way.

yarn create vite

It will ask you the name of the project, the framework to use and the variant (React and TypeScript).
To run the server, just do:

yarn dev

Now you are ready to start coding.

First, go to your project and install your dependencies (React, TypeScript, etc.) doing:

yarn

Then add the openai package.

yarn add openai

You might need to install the `@types/node` dependencies

yarn add @types/node --dev

I started modifying the React project. In my App.tsx file, I just kept this:

import React from 'react';
import reactLogo from './assets/react.svg';
import './App.css';

const App: React.FC = () => {
return (
<div className="App">
<div>
<a href="https://reactjs.org" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>React + Typescript + ChatGPT</h1>
</div>
);
};

export default App;

Then, I created a component named ChatGpt.tsx and imported it in my App.tsx file.

import React from 'react';
import { Configuration, OpenAIApi } from 'openai';

export const ChatGpt: React.FC = () => {
const configuration = new Configuration({
apiKey: 'MY_OPENAI_KEY',
});
const myOpenAi = new OpenAIApi(configuration);
return (
<>
{'Hello there!'}
</>
);
};
import React from 'react';
import reactLogo from './assets/react.svg';
import './App.css';
import { ChatGpt } from './ChatGpt';

const App: React.FC = () => {
return (
<div className="App">
<div>
<a href="https://reactjs.org" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>React + Typescript + ChatGPT</h1>
<ChatGpt />
</div>
);
};

export default App;

I created a simple form (a text field and a submit button) to talk to ChatGPT, and a box where I will show the response of the AI.

import React from 'react';
import { Configuration, OpenAIApi } from 'openai';

export const ChatGpt: React.FC = () => {
const [prompt, setPrompt] = React.useState<string | undefined>('');
const [response, setResponse] = React.useState<string | undefined>('');
const configuration = new Configuration({
apiKey: 'MY_OPENAI_KEY',
});
const myOpenAi = new OpenAIApi(configuration);
return (
<>
<form onSubmit={getOpenAIResponse}>
<input
id="chat-input"
type="text"
value={prompt}
onChange={e => setPrompt(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
{/* If there's no response then don't show the element,
we can replace it with a Loading comonent */}
{!!response && <div>{response}</div>}
</>
);
};

I added the getOpenAIResponse function and a simple messages array.
(You would want to read about Chat Completion to understand a little more about the messages array, https://platform.openai.com/docs/guides/chat).

import React from 'react';
import { ChatCompletionRequestMessageRoleEnum, Configuration, OpenAIApi } from 'openai';

export const ChatGpt: React.FC = () => {
const [prompt, setPrompt] = React.useState<string | undefined>('');
const [response, setResponse] = React.useState<string | undefined>('');
const configuration = new Configuration({
apiKey: 'MY_OPENAI_KEY',
});
const myOpenAi = new OpenAIApi(configuration);
const chatGptMessages = [
{
role: ChatCompletionRequestMessageRoleEnum.System,
content: !!prompt ? prompt : 'Hello',
}
];
const getOpenAIResponse = async (e: React.FormEvent<EventTarget>) => {
e.preventDefault();
const res = await myOpenAi.createChatCompletion({
messages: chatGptMessages,
model: 'gpt-3.5-turbo',
});
setResponse(res.data.choices[0].message?.content);
};
return (
<>
<form onSubmit={getOpenAIResponse}>
<input
id="chat-input"
type="text"
value={prompt}
onChange={e => setPrompt(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
{/* If there's no response then don't show the element */}
{!!response && <div>{response}</div>}
</>
);
};

And that’s it, a simple ask and respond ChatGPT made with React.

In a real-world application, you may want to add more error handling, loading state, and other features to make it more robust. Plus if you want to preserve the responses to help the assistant then you might need to work on a better chatGptMessages.

Here is the project in GitHub: https://github.com/andresz74/react_typescript_chatgpt

Have some fun trying it. 🙃

--

--