Build a ChatGPT Web App with GPT4
Apr 11, 2023

Below is the code that GPT4 generated when we asked it to create a ChatGPT web app, make sure you implement your OpenAI key so that you can make API calls. If you don't do this crucial step you will run into a ton of errors!
1. First, create a new React app using create-react-app:
npx create-react-app chatgpt-app
cd chatgpt-app
2. Install Axios to handle API requests:
npm install axios
3. In your src folder, create a new file named ChatGPT.js:
import React, { useState } from 'react';
import axios from 'axios';
const ChatGPT = () => {
const [input, setInput] = useState('');
const [responses, setResponses] = useState([]);
const handleInputChange = (e) => {
setInput(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!input) return;
try {
const response = await axios.post(
'https://api.openai.com/v1/engines/davinci-codex/completions',
{
prompt: input,
max_tokens: 150,
n: 1,
stop: null,
temperature: 1,
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
},
}
);
const message = response.data.choices[0].text.trim();
setResponses((prevResponses) => [...prevResponses, { input, message }]);
setInput('');
} catch (error) {
console.error('Error fetching response:', error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={input}
onChange={handleInputChange}
placeholder="Type your message..."
/>
<button type="submit">Send</button>
</form>
<div>
{responses.map((response, index) => (
<div key={index}>
<p>
<strong>You:</strong> {response.input}
</p>
<p>
<strong>ChatGPT:</strong> {response.message}
</p>
</div>
))}
</div>
</div>
);
};
export default ChatGPT;
4. Replace the content of src/App.js with the following:
import React from 'react';
import './App.css';
import ChatGPT from './ChatGPT';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>ChatGPT React App</h1>
</header>
<ChatGPT />
</div>
);
}
export default App;
5. Add your OpenAI API key to your .env file:
makefileCopy code
REACT_APP_OPENAI_API_KEY=your_openai_api_key_here
6. Finally, start the development server with npm start.
This basic setup will allow you to communicate with the ChatGPT API using React. Keep in mind that this example is for educational purposes only, and you should always consider security best practices when deploying applications that use sensitive API keys.
If you enjoyed this article we would love for you to check out our product ZoZo App which will allow you to get access to ChatGPT right from your iOS Keyboard. We're launching this feature this week! You can download ZoZo App by tapping the button below!