Build a Simple Next.js Interactive Web-Based Random Quote Generator

Written by

in

Tired of the same old inspirational quotes? Want a fresh dose of wisdom (or silliness) every time you visit a website? In this tutorial, we’ll build a simple, interactive Random Quote Generator using Next.js. This project is perfect for beginners and intermediate developers looking to hone their skills in Next.js, learn about API calls, and explore basic state management.

Why Build a Random Quote Generator?

Random Quote Generators are more than just a fun novelty; they’re a great way to learn fundamental web development concepts. This project will help you understand:

  • API Consumption: Fetching data from an external API.
  • State Management: Updating the UI based on fetched data.
  • Component Structure: Building reusable components.
  • Event Handling: Responding to user interactions (like clicking a button).
  • Basic Styling: Making your app look presentable.

Plus, it’s a relatively small project, making it ideal for quick learning and experimentation. Imagine embedding this on a personal website, a blog, or even a dashboard to add a touch of personality!

Prerequisites

Before we dive in, make sure you have the following:

  • Node.js and npm (or yarn) installed: These are essential for running Next.js.
  • Basic understanding of HTML, CSS, and JavaScript: Familiarity with these will make the tutorial easier to follow.
  • A code editor: VS Code, Sublime Text, or any editor you prefer.

Setting Up the Project

Let’s get started by creating a new Next.js project. Open your terminal and run the following command:

npx create-next-app random-quote-generator
cd random-quote-generator

This will create a new Next.js project named “random-quote-generator” and navigate you into the project directory.

Fetching Quotes from an API

We’ll use a free and public API to get our quotes. There are several options available. For this tutorial, we will use the Quotable API. It’s simple to use and provides a good variety of quotes.

First, let’s create a function to fetch the quotes. Open `pages/index.js` and add the following code inside the `function Home()` component, right before the `return` statement:

async function getQuote() {
  const response = await fetch('https://api.quotable.io/random');
  const data = await response.json();
  return data;
}

This `getQuote` function does the following:

  • `async function getQuote()`: Defines an asynchronous function to fetch the quote.
  • `const response = await fetch(‘https://api.quotable.io/random’);`: Makes a GET request to the Quotable API. The `await` keyword ensures the code waits for the response.
  • `const data = await response.json();`: Parses the JSON response from the API.
  • `return data;`: Returns the parsed data (which contains the quote and author).

Displaying the Quote

Now, let’s display the quote on our page. We’ll use the `useState` hook to manage the quote’s state. Modify the `pages/index.js` file as follows:

import { useState, useEffect } from 'react';

function Home() {
  const [quote, setQuote] = useState({
    content: "Loading...",
    author: ""
  });

  async function getQuote() {
    const response = await fetch('https://api.quotable.io/random');
    const data = await response.json();
    return data;
  }

  useEffect(() => {
    async function fetchQuote() {
      const newQuote = await getQuote();
      setQuote(newQuote);
    }
    fetchQuote();
  }, []);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', fontFamily: 'sans-serif' }}>
      <blockquote style={{ maxWidth: '600px', padding: '20px', border: '1px solid #ccc', borderRadius: '5px', marginBottom: '20px' }}>
        <p style={{ fontSize: '1.5em', margin: '0' }}>{quote.content}</p>
        <cite style={{ fontSize: '1em', textAlign: 'right', display: 'block', marginTop: '10px' }}>- {quote.author}</cite>
      </blockquote>
      <button style={{ padding: '10px 20px', fontSize: '1em', backgroundColor: '#0070f3', color: 'white', border: 'none', borderRadius: '5px', cursor: 'pointer' }} onClick={() => {
        async function updateQuote() {
          const newQuote = await getQuote();
          setQuote(newQuote);
        }
        updateQuote();
      }}>New Quote</button>
    </div>
  );
}

export default Home;

Let’s break down this code:

  • `import { useState, useEffect } from ‘react’;`: Imports the `useState` and `useEffect` hooks from React.
  • `const [quote, setQuote] = useState({…});`: Initializes the `quote` state variable with an object containing `content` and `author`. Initially, it displays “Loading…”.
  • `useEffect(() => { … }, []);`: This hook runs once when the component mounts (the `[]` as the second argument ensures this). Inside, it calls `getQuote()` to fetch a quote and updates the `quote` state using `setQuote()`.
  • `<blockquote>`: Displays the quote and author in a blockquote element.
  • `<button onClick={…}>`: A button that, when clicked, calls `getQuote()` again and updates the `quote` state with a new quote. It uses an inline function to call an `async` function, which is a common pattern in React to handle asynchronous operations within event handlers.

Styling the Application (Basic)

The code includes inline styles for basic formatting. Let’s briefly explain each style property used:

  • `display: ‘flex’`, `flexDirection: ‘column’`, `alignItems: ‘center’`, `justifyContent: ‘center’`, `minHeight: ‘100vh’`: This set of styles centers the content vertically and horizontally on the page.
  • `fontFamily: ‘sans-serif’`: Sets a default font.
  • `maxWidth: ‘600px’`, `padding: ’20px’`, `border: ‘1px solid #ccc’`, `borderRadius: ‘5px’`, `marginBottom: ’20px’`: Styles the blockquote container.
  • `fontSize: ‘1.5em’`, `margin: ‘0’`: Styles the quote text.
  • `fontSize: ‘1em’`, `textAlign: ‘right’`, `display: ‘block’`, `marginTop: ’10px’`: Styles the author citation.
  • `padding: ’10px 20px’`, `fontSize: ‘1em’`, `backgroundColor: ‘#0070f3’`, `color: ‘white’`, `border: ‘none’`, `borderRadius: ‘5px’`, `cursor: ‘pointer’`: Styles the button.

For more advanced styling, you can use CSS modules, styled-components, or a CSS framework like Tailwind CSS. For the sake of simplicity, we are using inline styles here, but for larger projects, consider using a CSS framework to streamline your styling process.

Running the Application

To run your application, open your terminal, navigate to your project directory (if you’re not already there), and run the following command:

npm run dev
# or
yarn dev

This will start the development server, and you can view your application in your browser at `http://localhost:3000` (or the port specified in your terminal).

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • CORS Errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, it means your browser is blocking the request to the API. This usually happens when the API server doesn’t allow requests from your domain. While developing, you might be able to use a CORS proxy (there are browser extensions available). For production, you’ll need to configure your server to handle CORS properly. The Quotable API, in this case, does not have any CORS restrictions.
  • API Request Failing: Double-check the API endpoint URL. Make sure you’ve spelled it correctly. Also, inspect the browser’s developer console (usually by right-clicking and selecting “Inspect” or “Inspect Element”) to look for any network errors.
  • Quote Not Displaying: Make sure the `quote` state is being updated correctly. Use `console.log(quote)` inside the `useEffect` hook and the `onClick` handler for the button to see what data is being fetched and stored.
  • Missing Dependencies: Ensure you have the necessary dependencies installed. If you encounter an error related to a missing module, try running `npm install [module-name]` or `yarn add [module-name]`.

Enhancements and Next Steps

Once you’ve built the basic Random Quote Generator, you can explore these enhancements:

  • Add a Share Button: Implement buttons to share the quote on social media platforms like Twitter or Facebook.
  • Implement Categories: Allow users to filter quotes by category (e.g., “inspirational”, “funny”, “love”). This would require an API that supports categories.
  • Improve Styling: Use CSS modules, styled-components, or a CSS framework like Tailwind CSS for more visually appealing design.
  • Error Handling: Implement error handling to gracefully handle API errors (e.g., display an error message if the API is unavailable).
  • Persist Quotes: Store the quotes in local storage so the user can see the same quote on refresh.

Summary / Key Takeaways

This tutorial demonstrated how to build a basic Random Quote Generator using Next.js. We covered:

  • Setting up a Next.js project.
  • Fetching data from an external API.
  • Using the `useState` and `useEffect` hooks for state management and side effects.
  • Rendering data in a React component.
  • Handling user interactions (button clicks).
  • Basic styling.

This project provides a solid foundation for building more complex applications in Next.js. Remember to practice these concepts to become more proficient. Experiment with different APIs, styling techniques, and features to expand your knowledge. The ability to fetch and display data from APIs is a core skill in modern web development, and this project provides a clear, practical introduction. By understanding these fundamentals, you’ll be well-equipped to tackle more ambitious projects.

FAQ

Q: Where can I find more free APIs?

A: There are many resources for finding free APIs. Some popular sites include:

Q: How can I debug my Next.js application?

A: The browser’s developer console is your best friend. You can use `console.log()` statements to inspect variables and see what’s happening in your code. You can also use the “Sources” tab to set breakpoints and step through your code. React Developer Tools (a browser extension) can be helpful for inspecting React components.

Q: How do I deploy my Next.js application?

A: Next.js applications are often deployed to platforms like Vercel (which is recommended, as it’s built by the creators of Next.js), Netlify, or AWS. You’ll typically push your code to a Git repository (like GitHub or GitLab) and configure the deployment platform to build and deploy your application automatically. Check the documentation for your chosen platform for specific instructions.

Q: Can I use CSS frameworks like Tailwind CSS with Next.js?

A: Yes! Next.js integrates very well with CSS frameworks. You can install them using npm or yarn and then configure them in your project. For example, to use Tailwind CSS, you would install it and then configure your `tailwind.config.js` and `postcss.config.js` files. The Next.js documentation provides detailed instructions.

Building this Random Quote Generator is just the beginning. The skills you’ve learned here—fetching data, managing state, and handling user interactions—are fundamental to modern web development. As you continue to build projects and explore new technologies, you’ll solidify these concepts and develop a strong foundation for your future endeavors. Keep experimenting, keep learning, and most importantly, keep building!