Introduction
In this tutorial, we will be creating a simple random image generator using the Pixabay API and React. The Pixabay API is a free API that allows us to search for and retrieve images from the Pixabay image database. We will be using the Axios library to make HTTP requests to the Pixabay API and the ReactJS library to build the user interface for our image generator.
Prerequisites
Before we begin, you will need to have the following prerequisites installed on your development machine:
- Node.js and npm (the Node.js package manager)
- A text editor (such as Visual Studio Code)
- A web browser (such as Google Chrome)
Step 1: Setting Up the Project
First, we need to create a new React project. Open a terminal window and navigate to the directory where you want to create your project. Then, run the following command to create a new React project using the create-react-app
tool:
npx create-react-app random-image-generator
This will create a new directory called random-image-generator
with the basic files and folders needed for a React project. Navigate to the project directory:
cd random-image-generator
Next, we need to install the Axios library, which we will use to make HTTP requests to the Pixabay API. Run the following command to install Axios:
npm install axios
Step 2: Obtaining a Pixabay API Key
Before we can use the Pixabay API, we need to obtain an API key. Go to the Pixabay API page and sign up for a free API key. Once you have your API key, keep it handy as we will need it later.
Step 3: Fetching Images from the Pixabay API
Now that we have our API key and the necessary libraries installed, we can start fetching images from the Pixabay API.
First, let’s create a new file called api.js
in the src
directory. This file will contain the code for making HTTP requests to the Pixabay API.
In api.js
, import the Axios library and create a new function called fetchRandomImage
that takes in a search term and returns a random image from the Pixabay API:
import axios from 'axios';
const API_KEY = 'YOUR_API_KEY_HERE'; // Replace with your own API key
export async function fetchRandomImage(searchTerm) {
const response = await axios.get(
`https://pixabay.com/api/?key=${API_KEY}&q=${searchTerm}&per_page=100`
);
const images = response.data.hits;
if (images.length === 0) {
throw new Error(`No images found for search term: ${searchTerm}`);
}
// Return a random image from the search results
return images[Math.floor(Math.random() * images.length)];
}
Step 4: Creating the User Interface
Now that we have the ability to fetch random images from the Pixabay API, we can start building the user interface for our image generator.
Open the src/App.js
file and replace the contents with the following code:
import React, { useState } from 'react';
import { fetchRandomImage } from './api';
function App() {
const [image, setImage] = useState(null);
const [searchTerm, setSearchTerm] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
async function handleSearch(e) {
e.preventDefault();
setIsLoading(true);
setError(null);
try {
const image = await fetchRandomImage(searchTerm);
setImage(image);
} catch (error) {
setError(error.message);
} finally {
setIsLoading(false);
}
}
return (
<div className="App">
<form onSubmit={handleSearch}>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button type="submit" disabled={isLoading}>
Search
</button>
</form>
{isLoading && <p>Loading...</p>}
{error && <p>{error}</p>}
{image && (
<div>
<h2>{image.tags}</h2>
<img src={image.webformatURL} alt={image.tags} />
</div>
)}
</div>
);
}
export default App;
This code creates a simple form with an input field and a search button. When the form is submitted, the handleSearch
function is called, which makes a request to the Pixabay API using the fetchRandomImage
function we created earlier. The response from the API is then used to update the state of the component with the image data.
The component also has a few state variables to keep track of the search term, whether the request is still loading, any errors that may occur, and the image data itself. These state variables are used to display a loading message, an error message, or the image and its tags depending on the current state of the component.
Step 5: Testing the Image Generator
Now that we have all the code in place, we can test our image generator by running the following command in the terminal:
npm start
This will start the development server and open a new browser window with the image generator. Try searching for different terms to see a random image from the search results.
Conclusion
In this tutorial, we learned how to create a simple random image generator using the Pixabay API and React. We used the Axios library to make HTTP requests to the API and the ReactJS library to build the user interface.
I hope this tutorial was helpful and that you were able to successfully create your own.