Building a Random Quote Generator App in React

Overview

In this tutorial, we’ll walk through the process of creating a simple web application using React that fetches random quotes based on selected categories from an external API. We’ll cover how to set up the project, create components, manage state, handle user input, and fetch data from an API.

Prerequisites:

Before getting started, make sure you have Node.js , npm (Node Package Manager) and Vite installed on your system.

Step 1: Setting up the project:

Setting Up the Project First, let’s set up a new React project using Create React App. Open your terminal and run the following command:

				
					npm create vite@latest quote-generator-app
				
			

Once the project is created, navigate into the project directory:

				
					cd quote-generator-app
				
			

Open VsCode by typing the following command in terminal:

Note: After creating the project folder , go to package.json and rechange the “dev” field to “start

				
					code .
				
			

Step 2: Creating components:

Create a Components and router folder inside the src folder

Creating Components Now, let’s create two new components: CategoryOptions.jsx and Quotes.jsx.

In CategoryOptions.jsx, we’ll define a component that represents a single option in the category dropdown menu.

				
					
import React from "react";

const CategoryOptions = ({ value }) => {
  return <option value={value}>{value}</option>;
};

export default CategoryOptions;

				
			

In Quotes.jsx, we’ll create the main component where the quote generation functionality resides.

				
					// Quotes.js
import React, { useState } from "react";
import CategoryOptions from "./CategoryOptions";

const Quotes = () => {
  // State variables
  const [cat, setCategory] = useState("");
  const [data, setData] = useState("");
  const [author, setAuthor] = useState("");

  // Function to fetch quotes from API
  const requestAPI = async () => {
    const url = `https://api.api-ninjas.com/v1/quotes?category=${cat}`;
    const requestedURL = await fetch(url, {
      method: "Get",
      headers: {
        "X-Api-Key": "YOUR_API_KEY_HERE",
      },
    });
    let apiResponse = await requestedURL.json();
    const [{ quote, author, category }] = apiResponse;
    setData(quote);
    setCategory(category);
    setAuthor(author);
  };

  // Function to handle category selection
  const onHandleClick = (event) => {
    setCategory(event.target.value);
  };

  return (
    <>
      <h2>Choose your today's quote on</h2>
      {/* Category dropdown menu */}
      <select value={cat} onChange={onHandleClick} name="quote-category">
        {/* Render options dynamically */}
        <CategoryOptions value="age" />
        {/* Add more options as needed */}
      </select>
      <div>
        {/* Button to confirm category selection */}
        <button onClick={requestAPI}>Confirm</button>
      </div>
      {/* Display quote, author, and category */}
      {data !== "" ? (
        <div>
          <h4>
            <strong>Quote:</strong> {data}
          </h4>
          <h5>Author: {author}</h5>
          <h6>Category: {cat}</h6>
        </div>
      ) : (
        // Display message if no option chosen
        <h3>No option chosen.</h3>
      )}
    </>
  );
};

export default Quotes;

				
			

Step 3: Setting up of MainRouter.jsx:

Inside the router folder create a MainRouter.jsx file with the following content.

				
					import React from 'react'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import Quotes from '../Components/Quotes'

const mainRouter = () => {
    return (
        <BrowserRouter>
            <Routes>
                {/* Render Quotes component on "/" path */}
                <Route path="/" element={<Quotes />} />
                {/* Remove rendering of Quotes component from "/quotes" path */}
            </Routes>
        </BrowserRouter>
    )
}

export default mainRouter
				
			

Step 4: Styling:

You can add CSS styling to enhance the appearance of your components and make the user interface more appealing.

Step 5: Changing the default component rendered on ” / ” path:

Don’t forget to replace the main.jsx code with the following code. 

				
					import React from 'react'
import ReactDOM from 'react-dom/client'

import './index.css'
import MainRouter from './router/MainRouter.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <MainRouter />
  </React.StrictMode>,
)

				
			

Step 6: Running the Application:

To run the application, use the following command:

				
					npm start
				
			

Conclusion:

Congratulations! You’ve successfully built a random quote generator app using React. You’ve learned how to set up a React project, create components, manage state, handle user input, and fetch data from an API. Feel free to expand upon this project by adding more features or customizations according to your preferences.