Create AI App Using React js and Open AI (Content Generator)

1 year ago admin Reactjs

In this tutorial, we are going to create a content generator using react js and Open AI, I assume that you have already created 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 [textInput, setTextInput] = useState("");
  const [text, setText] = useState("");
  //open ai config
  const { Configuration, OpenAIApi } = require("openai");
  const configuration = new Configuration({
    apiKey: "YOUR API KEY",
  });
  const openai = new OpenAIApi(configuration);

  const fetchText = async (e) => {
    e.preventDefault();
    try {
      const response = await openai.createCompletion({
        model: "text-davinci-003",
        prompt: textInput,
        max_tokens: 1000,
        temperature: 0.2,
      });
      setText(response.data.choices[0].text);
      setTextInput("");
    } 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 Text
              </div>
            </div>
            <div className="card-body">
              <div className='my-3'>
                  <p className="fw-bold">
                    {text}
                  </p>
              </div>
              <form onSubmit={(e) => fetchText(e)}>
                <div className="form-group mb-3">
                  <textarea rows="5" cols="30"
                    value={textInput}
                    onChange={(e) => setTextInput(e.target.value)}
                    className='form-control' placeholder='Start typing...'></textarea>
                </div>
                <div className="form-group mb-3">
                  <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:

Demo


                                                            
                                                                                                                                
<!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>

Related Tuorials

How to Use Rich Text Editor in React js

In this lesson, we will see how to use rich text editor in React JS, let's assume that we have a com...


How to Download a File from the Server Using Laravel and React js

In this tutorial, we will see how to download a file from the server using Laravel and React js, let...


How to Add a Class on Hover in React js

In this lesson, we will see how to add a class on hover in React js, let's assume that we have a boo...


Drag and Drop Image and File Upload Using React and Laravel

In this tutorial, we will see how to upload files using drag and drop in React js and Laravel, first...


API Authentication Using Laravel Sanctum and React js Part 3

In the third part of this tutorial, we will register and log in the user, get the access token, and...


API Authentication Using Laravel Sanctum and React js Part 2

In the second part of this tutorial, we will start handling the frontend first, we will create the r...


API Authentication Using Laravel Sanctum and React js Part 1

In today's tutorial, we are going to see how to create a token-based authentication system using Lar...


How to Update Nested Array with Hooks in React

In this lesson, we will see how to update nested array with hooks in React, let's assume that we hav...


How to Set the Loading State Only on a Specific Clicked Button in React

In this lesson, we will see how to set the loading state only on a specific clicked button in React,...


Create a Rest API in PHP and Consume it in React Part 5

In the fifth part of this tutorial, we will add routes to our application and finally, we will add s...