Building a Quote Generator in React: A Beginner's Guide

WHAT TO KNOW - Sep 9 - - Dev Community

<!DOCTYPE html>





Building a Quote Generator in React: A Beginner's Guide

<br> body {<br> font-family: sans-serif;<br> margin: 0;<br> padding: 20px;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code>h1, h2, h3 { margin-top: 30px; } code { background-color: #f5f5f5; padding: 5px; border-radius: 3px; } pre { background-color: #f5f5f5; padding: 10px; border-radius: 3px; overflow-x: auto; } .image-container { text-align: center; margin-bottom: 20px; } .image-container img { max-width: 100%; height: auto; } .quote-container { border: 1px solid #ccc; padding: 20px; margin-bottom: 20px; border-radius: 5px; } .quote-text { font-size: 1.2em; font-style: italic; margin-bottom: 10px; } .quote-author { font-weight: bold; text-align: right; } </code></pre></div> <p>



Building a Quote Generator in React: A Beginner's Guide



Quote generators are simple yet fun applications that can bring a touch of inspiration or humor to your website or app. In this guide, we'll walk you through the process of building a basic quote generator using React, a popular JavaScript library for building user interfaces.



Why React?



React is an excellent choice for building dynamic web applications like quote generators due to its:



  • Component-based architecture:
    React encourages breaking down your application into reusable components, making it easy to manage and maintain.

  • Virtual DOM:
    React's virtual DOM efficiently updates the real DOM, optimizing performance.

  • JSX:
    JSX allows you to write HTML-like syntax within your JavaScript code, enhancing readability and productivity.


Project Setup



Before we start coding, we need to set up our React project. We'll use Create React App, a tool that provides a pre-configured environment for React development. Here's how to get started:



  1. Install Node.js and npm (or yarn):
    Make sure you have Node.js and its package manager npm (or yarn) installed on your system. You can download them from
    https://nodejs.org/ .

  2. Create a React project:
    Open your terminal and run the following command to create a new React project:

  3. npx create-react-app quote-generator

  4. Navigate to the project directory:

  5. cd quote-generator

  6. Start the development server:

  7. npm start


    This will open your project in the browser at

    http://localhost:3000/

    .



Creating the Quote Component



Now, let's create our main component,

Quote.jsx

, which will display a random quote. Open

src/App.js

and replace its contents with the following code:



import React, { useState } from 'react';
import './App.css';
function Quote() {
  const [quote, setQuote] = useState('');
  const [author, setAuthor] = useState('');

  const getQuote = () =&gt; {
    // Fetch a random quote from an API (you'll need to replace this)
    fetch('https://api.quotable.io/random')
      .then(response =&gt; response.json())
      .then(data =&gt; {
        setQuote(data.content);
        setAuthor(data.author);
      });
  };

  return (
    <div classname="quote-container">
      <p classname="quote-text">{quote}</p>
      <p classname="quote-author">- {author}</p>
      <button onclick="{getQuote}">New Quote</button>
    </div>
  );
}

export default Quote;


Here's what this code does:



  • Import necessary modules:
    We import the
    useState
    hook from React for managing state (the quote and author) and
    './App.css'
    for styling.

  • Create a functional component:
    The
    Quote
    component is a functional component defined using the
    function
    keyword.

  • State variables:

    useState
    is used to initialize two state variables:
    quote
    and
    author
    . These will store the fetched quote and author.

  • Fetch random quote:
    The
    getQuote
    function makes a fetch request to a random quote API (you can replace this with your preferred API). It then updates the
    quote
    and
    author
    state variables with the received data.

  • Render the quote:
    The component renders a
    div
    containing the quote and author, along with a button that triggers the
    getQuote
    function when clicked.


Let's add some basic styling in

src/App.css

:



.quote-container {
border: 1px solid #ccc;
padding: 20px;
margin-bottom: 20px;
border-radius: 5px;
}
.quote-text {
  font-size: 1.2em;
  font-style: italic;
  margin-bottom: 10px;
}

.quote-author {
  font-weight: bold;
  text-align: right;
}


Now, you can run

npm start

again to see your basic quote generator in action! Every time you click the "New Quote" button, it fetches and displays a new quote.



Adding More Features


  1. Using a Different Quote API

You can choose from various free quote APIs available online. Here are a few popular options:

To use a different API, simply replace the URL in the getQuote function with the correct API endpoint. For example, using the type.fit API:

fetch('https://type.fit/api/quotes')
  .then(response => response.json())
  .then(data => {
    setQuote(data[Math.floor(Math.random() * data.length)].text);
    setAuthor(data[Math.floor(Math.random() * data.length)].author);
  });

  • Filtering Quotes by Author or Category

    To enhance functionality, you can add filtering options to the quote generator. For instance, let's add a filter to show quotes from a specific author. We'll use another API to get a list of authors and then use that information for filtering.

    First, create a new component for author selection, AuthorFilter.jsx :

    import React, { useState, useEffect } from 'react';
    
    function AuthorFilter({ onAuthorChange }) {
      const [authors, setAuthors] = useState([]);
    
      useEffect(() => {
        fetch('https://type.fit/api/quotes') // Replace with your author API
          .then(response => response.json())
          .then(data => {
            const uniqueAuthors = new Set();
            data.forEach(quote => {
              if (quote.author) {
                uniqueAuthors.add(quote.author);
              }
            });
            setAuthors([...uniqueAuthors]);
          });
      }, []);
    
      return (
         onAuthorChange(event.target.value)}>
          All Authors
          {authors.map(author => (
            
              {author}
            
          ))}
        
      );
    }
    
    export default AuthorFilter;
    

    This component fetches a list of authors (using the same type.fit API), stores them in state, and renders a dropdown for selecting an author.

    Now, modify Quote.jsx to include the AuthorFilter and to filter quotes based on the selected author:

    import React, { useState, useEffect } from 'react';
    import AuthorFilter from './AuthorFilter';
    import './App.css';
    
    function Quote() {
      const [quote, setQuote] = useState('');
      const [author, setAuthor] = useState('');
      const [selectedAuthor, setSelectedAuthor] = useState('');
    
      const getQuote = () => {
        fetch('https://api.quotable.io/random')
          .then(response => response.json())
          .then(data => {
            setQuote(data.content);
            setAuthor(data.author);
          });
      };
    
      useEffect(() => {
        if (selectedAuthor) {
          fetch(`https://api.quotable.io/random?author=${selectedAuthor}`) // Filter by author
            .then(response => response.json())
            .then(data => {
              setQuote(data.content);
              setAuthor(data.author);
            });
        } else {
          getQuote();
        }
      }, [selectedAuthor]);
    
      return (
        
          
          

    {quote}

    - {author}

    New Quote ); } export default Quote;

    In Quote.jsx , we add a new state variable, selectedAuthor , to track the chosen author from the dropdown. The useEffect hook now conditionally fetches quotes, either by author (if selectedAuthor is not empty) or randomly (otherwise). The onAuthorChange prop in AuthorFilter updates selectedAuthor whenever the dropdown selection changes.


  • Adding Styling and Visuals

    You can further enhance the user experience by adding styling and visual elements to the quote generator. You can use CSS to customize the appearance of the quote container, text, button, and author. You could also use libraries like Font Awesome to add icons, or consider adding background images or animations to make it more visually appealing. Here's an example using Font Awesome:

    First, install Font Awesome:

    npm install @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome
    

    Then, import the necessary components and add an icon to the button:

    import React, { useState, useEffect } from 'react';
    import AuthorFilter from './AuthorFilter';
    import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
    import { faQuoteLeft } from '@fortawesome/free-solid-svg-icons';
    import './App.css';
    
    function Quote() {
      // ... (rest of the code)
    
      return (
        
          {/* ... (rest of the content) */}
          
             New Quote
          
        
      );
    }
    
    export default Quote;
    

    Conclusion

    Building a quote generator in React is a great way to learn the basics of React development and create a fun, interactive application. We've explored key concepts like component-based architecture, state management, and data fetching using APIs. You can build upon this foundation to add more features, customize the design, and create a truly engaging quote generator.

    Remember to choose an API that suits your needs, experiment with different styling and visual elements, and most importantly, have fun exploring the creative possibilities with React!

  • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .