Integrating ChatGPT into a React search bar can be achieved by using the OpenAI API
Muhammad Arslan
SSE | Node JS | React JS | Typescript | MERN Stack | Nest js | Next js | Svelte (senior full stack developer )
Here are the general steps you can follow:
import React, { useState } from "react";
import axios from "axios";
function SearchBar() {
?const [searchQuery, setSearchQuery] = useState("");
?const [chatGPTResponse, setChatGPTResponse] = useState("");
?const handleSubmit = async (event) => {
??event.preventDefault();
??const response = await axios.post(
???"https://api.openai.com/v1/engine/chat",
???{
????prompt: searchQuery,
????temperature: 0.7,
????max_tokens: 150,
????top_p: 1,
????frequency_penalty: 0,
????presence_penalty: 0,
???},
???{
????headers: {
?????Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
????},
???}
??);
??setChatGPTResponse(response.data.choices[0].text);
?};
?return (
??<form onSubmit={handleSubmit}>
???<input
????type="text"
????placeholder="Search..."
????value={searchQuery}
????onChange={(event) => setSearchQuery(event.target.value)}
???/>
???<button type="submit">Search</button>
???{chatGPTResponse && (
????<div>
?????<p>{chatGPTResponse}</p>
????</div>
???)}
??</form>
?);
}
export default SearchBar;