Create AI App Using React js and Open AI (Image Generator)
In this tutorial, we are going to create an image generator using react js and Open AI, I assume that you have already a new react js application and you have also a user account at https://openai.com/.
Add the Open AI package
First, we need to install the Open AI package.
npm install openai
Update App.js
First, you need to grab your API key from here next, we will update the App Component and add the following code:
import { useState } from 'react';
import './App.css';
function App() {
const [image, setImage] = useState("http://via.placeholder.com/640x360");
const [imageInput, setImageInput] = useState("");
const [loading, setLoading] = useState(false);
//open ai config
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: "YOUR API KEY",
});
const openai = new OpenAIApi(configuration);
const fetchImage = async (e) => {
e.preventDefault();
setLoading(true);
try {
const response = await openai.createImage({
prompt: imageInput,
n: 1,
size: "1024x1024",
});
setImage(response.data.data[0].url);
setImageInput("");
setLoading(false);
} catch (error) {
console.error(error);
}
}
return (
<div className="container">
<div className="row my-4">
<div className="col-md-6">
<div className="card">
<div className="card-header text-center">
<div>
Generate Image
</div>
</div>
<div className="card-body">
<div className='my-3'>
{
loading ?
<div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
:
<img src={image} className='img-fluid' alt="" srcset="" />
}
</div>
<form onSubmit={(e) => fetchImage(e)}>
<div className="form-group mb-3">
<input type="text"
value={imageInput}
onChange={(e) => setImageInput(e.target.value)}
className='form-control' placeholder='Search...'/>
</div>
<div className="form-group mb-3">
{
loading ?
<div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
:
<button type="submit" className="btn btn-sm btn-primary">
submit
</button>
}
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
Add bootstrap 5 to our react project
Next, let's add bootstrap 5 to our application, now if you run npm start you will see the following result:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>React Open Ai App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>