AI-powered image generation has become a fascinating field, with tools like OpenAI's DALL·E allowing developers to create stunning visuals from simple text prompts. In this quick guide, we’ll explore how to integrate DALL·E’s API into a React application to generate images dynamically in the browser. Prerequisites Before we begin, ensure you have the following: Node.js installed on your system An OpenAI API key - You can create one here Basic knowledge of TypeScript and React Node.js installed on your system An OpenAI API key - You can create one here here Basic knowledge of TypeScript and React Setting Up the React App If you don’t have a React project already, you can create one using Vite: npm create vite@latest ai-image-generator --template react-ts cd ai-image-generator npm install npm create vite@latest ai-image-generator --template react-ts cd ai-image-generator npm install Installing Required Dependencies We’ll need Axios to make API requests: npm install axios npm install axios Configuring Environment Variables Create a .env file in the root of your project, and add your OpenAI API key: .env VITE_OPENAI_API_KEY=your-openai-api-key VITE_OPENAI_API_KEY=your-openai-api-key Creating an OpenAI API Service First, create a new file apiService.ts to handle API requests: apiService.ts import axios from 'axios'; const API_KEY = import.meta.env.VITE_OPENAI_API_KEY; const API_URL = 'https://api.openai.com/v1/images/generations'; export const generateImage = async (prompt: string): Promise<string | null> => { try { const response = await axios.post( API_URL, { prompt, n: 1, size: '1024x1024', }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, } ); return response.data.data[0].url; } catch (error) { console.error('Error generating image:', error); return null; } }; import axios from 'axios'; const API_KEY = import.meta.env.VITE_OPENAI_API_KEY; const API_URL = 'https://api.openai.com/v1/images/generations'; export const generateImage = async (prompt: string): Promise<string | null> => { try { const response = await axios.post( API_URL, { prompt, n: 1, size: '1024x1024', }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, } ); return response.data.data[0].url; } catch (error) { console.error('Error generating image:', error); return null; } }; Building the React Component Create a new component ImageGenerator.tsx: ImageGenerator.tsx import React, { useState } from 'react'; import { generateImage } from './apiService'; import './ImageGenerator.css'; const ImageGenerator: React.FC = () => { const [prompt, setPrompt] = useState<string>(''); const [imageUrl, setImageUrl] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const handleGenerate = async () => { setLoading(true); const url = await generateImage(prompt); if (url) setImageUrl(url); setLoading(false); }; return ( <div className="container"> <h2>AI-Powered Image Generator</h2> <input type="text" className="input-box" placeholder="Enter a prompt..." value={prompt} onChange={(e) => setPrompt(e.target.value)} /> <button className="generate-button" onClick={handleGenerate} disabled={loading}> {loading ? 'Generating...' : 'Generate Image'} </button> {imageUrl && <img className="generated-image" src={imageUrl} alt="Generated" />} </div> ); }; export default ImageGenerator; import React, { useState } from 'react'; import { generateImage } from './apiService'; import './ImageGenerator.css'; const ImageGenerator: React.FC = () => { const [prompt, setPrompt] = useState<string>(''); const [imageUrl, setImageUrl] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const handleGenerate = async () => { setLoading(true); const url = await generateImage(prompt); if (url) setImageUrl(url); setLoading(false); }; return ( <div className="container"> <h2>AI-Powered Image Generator</h2> <input type="text" className="input-box" placeholder="Enter a prompt..." value={prompt} onChange={(e) => setPrompt(e.target.value)} /> <button className="generate-button" onClick={handleGenerate} disabled={loading}> {loading ? 'Generating...' : 'Generate Image'} </button> {imageUrl && <img className="generated-image" src={imageUrl} alt="Generated" />} </div> ); }; export default ImageGenerator; Adding Styles Create a new file ImageGenerator.css, and add the following styles: ImageGenerator.css .container { display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 20px; } .input-box { width: 80%; max-width: 400px; padding: 10px; margin: 10px 0; border: 2px solid #ccc; border-radius: 5px; font-size: 16px; } .generate-button { padding: 10px 15px; font-size: 16px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s; } .generate-button:hover { background-color: #0056b3; } .generate-button:disabled { background-color: #ccc; cursor: not-allowed; } .generated-image { margin-top: 20px; width: 100%; max-width: 512px; height: auto; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } .container { display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 20px; } .input-box { width: 80%; max-width: 400px; padding: 10px; margin: 10px 0; border: 2px solid #ccc; border-radius: 5px; font-size: 16px; } .generate-button { padding: 10px 15px; font-size: 16px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s; } .generate-button:hover { background-color: #0056b3; } .generate-button:disabled { background-color: #ccc; cursor: not-allowed; } .generated-image { margin-top: 20px; width: 100%; max-width: 512px; height: auto; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } Integrating the Component Modify App.tsx to include the ImageGenerator component: App.tsx ImageGenerator import React from 'react'; import ImageGenerator from './ImageGenerator'; import './App.css'; const App: React.FC = () => { return ( <div className="app-container"> <h1>AI Image Generator with React and DALL·E</h1> <ImageGenerator /> </div> ); }; export default App; import React from 'react'; import ImageGenerator from './ImageGenerator'; import './App.css'; const App: React.FC = () => { return ( <div className="app-container"> <h1>AI Image Generator with React and DALL·E</h1> <ImageGenerator /> </div> ); }; export default App; Running the Application Start your development server: npm run dev npm run dev Open the application in your browser, enter a prompt, and click Generate Image to see AI-powered image generation in action! Generate Image GitHub Repository You can find the complete source code for this project on GitHub: AI Image Generator Repository. AI Image Generator Repository Conclusion Integrating AI-powered image generation into your React application is simple with OpenAI’s DALL·E API. With further enhancements like prompt fine-tuning, image styling, and different resolutions, you can create more interactive and dynamic experiences for users. Try extending this project with more features and share your results!