Creating an Image Generator with React and OpenAI API: A Step-by-Step Guide
Beto, January 31, 2023 · 10,531 views
Learn how to create an image generator app with React and the OpenAI API. You'll learn everything from setting up your OpenAI developer account and API key to building the React app that sends prompts and displays generated images.
If you want to explore AI-powered image generation and integrate it into your React projects, this step-by-step guide will help you get started quickly and understand the key concepts and API usage.
What's inside
- Introduction to OpenAI API and image generation
- Creating an OpenAI developer account and managing API keys
- Setting up a new React app with Vite and installing dependencies
- Configuring environment variables for the API key
- Using the OpenAI JavaScript client to create images
- Building the React UI with state and event handlers
- Handling API responses and displaying generated images
- Tips on API usage costs and best practices
Introduction to OpenAI API and image generation
I open by highlighting the excitement around AI tools like ChatGPT and DALL·E, and introduces the OpenAI API as a way to generate images programmatically. The focus is on using the image generation endpoint to create unique images from text prompts.
Each time you generate an image with the same prompt, the API returns a different result, ensuring variety for users. The tutorial specifically uses 512x512 pixel images, which cost about two cents per image, making it affordable for experimentation.
Creating an OpenAI developer account and managing API keys
To follow along, you need to create a developer account at beta.openai.com. New users get some free credits, but after that, you must add a payment method to continue using the API.
Once logged in, you navigate to your profile’s API keys section to create a new secret key. It’s crucial to copy this key immediately because you won’t be able to see it again. I stress keeping this key private and never committing it to public repositories like GitHub to avoid unauthorized usage.
Setting up a new React app with Vite and installing dependencies
The tutorial uses Vite to quickly scaffold a new React app. The command used is , selecting React and JavaScript as the framework and language.
After creating the project, the OpenAI JavaScript client library is installed with . Running ensures all dependencies are installed. The project is then opened in Visual Studio Code for development.
Configuring environment variables for the API key
The API key is stored in an environment variable file named (or ) to keep it secure and separate from the codebase. I show how to prefix the variable with so Vite can expose it to the client-side code.
In the React app, the environment variable is accessed using . This setup prevents the key from being hardcoded and allows easy changes without code edits.
Using the OpenAI JavaScript client to create images
The OpenAI client is initialized by importing and from the package. A configuration object is created with the API key, then passed to instantiate the OpenAI API client.
An asynchronous function is defined to call , passing an object with the prompt text, number of images (), and image size (). The response contains URLs for the generated images, which can be extracted and used in the app.
Building the React UI with state and event handlers
The UI consists of a simple header, an input field for the prompt, a button to trigger image generation, and an image display area.
React state hooks manage the prompt input and the current image URL. When the user clicks the generate button, the async function is called to fetch a new image. The returned URL is saved in state and rendered in an tag.
This approach keeps the UI responsive and updates the image dynamically after each request.
Handling API responses and displaying generated images
I demonstrate logging the full API response to understand its structure. The key data needed is the URL of the first generated image, found at .
Error handling is implemented with a try-catch block around the API call, logging any errors to the console. This ensures the app can gracefully handle failures without crashing.
Tips on API usage costs and best practices
I mention that generating images costs money after free credits are used, roughly two cents per 512x512 image. I recommend monitoring usage in your OpenAI account dashboard.
Since image generation can take a few seconds, I suggest adding loading states or messages to improve user experience. Also, it warns about the expense of running the API and advises considering monetization if building a commercial product.
Resources

CourseReact course
Learn React fundamentals and build projects with practical examples.
Like this article? Get the rest of the library plus weekly React Native tips. Free.