Build A Random Quote Generator In React JS | React Project For Beginners



Welcome to my website U-GINE MEDIA. In this website I teach tutorials and share source code on some programming (HTML, CSS, JavaScript, React) tutorials. 

Before we get started, do well to subscribe to my channel to never miss out on any update that I post every single day.

You can also visit my GitHub where I upload all the code I have.

In this tutorial topic "", we will learn how to create it following these simple easy steps.

Share this to your programmer friends. If y'all learnt something today, make sure to let me in the comments. 

Get Source Code.

If interested in watching the video before running the code below, you can click the play button to get started.



Setting Up the Project

Before building the Quote Generator with React.js and CSS, ensure Node.js is installed on your computer. If not, download and install it from the official Node.js website.

Create a Project Folder:

  1. Make a new folder, for instance, “quote-generator”.
  2. Open this folder in your VS Code editor.

Initialize the Project:

Open your terminal by pressing Ctrl + J and then use Vite to create a new React app with this command:

  npm create vite@latest ./ -- --template react


Install necessary dependencies and start the development server:

npm install
npm run dev

If your project is running in your browser, congratulations! You’ve successfully set up your weather app. Now, let’s move on to modifying folders and files.

Modify folder and CSS Files:

  1. Remove the default assets folder and App.css file.
  2. Replace the content of index.css with the provided CSS code.


@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  min-height: 100vh;
  background: #101623;
  display: flex;
  justify-content: center;
  align-items: center;
}

.quote-generator {
  max-width: 1000px;
  background: #101623;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 20px;
  box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.1),
    -1px -1px 2px rgba(255, 255, 255, 0.1);
}

.quote-generator h1 {
  font-size: 2.7em;
  background: linear-gradient(to right, #1d7efd, #8f6fff);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-align: center;
}

.pre-message {
  text-align: center;
  color: #fff;
}

.quote {
  background: #283045;
  padding: 15px;
  border-radius: 5px;
  color: #fff;
  margin-top: 20px;
}

.quote p {
  font-size: 0.9em;
  line-height: 1.5em;
  max-width: 800px;
}

.quote > div {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.quote span {
  font-size: 0.9em;
}

.quote button {
  padding: 3px 15px;
  cursor: pointer;
  border: none;
  border-radius: 2px;
  text-transform: capitalize;
  background: #333e58;
  color: #fff;
}

.quotes {
  margin-top: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  gap: 1em;
}

.quotes .q {
  background: #333e58;
  padding: 15px;
  border-radius: 5px;
  color: #fff;
  max-width: 200px;
}

.quotes .q p {
  font-size: 0.9em;
  height: 120px;
  overflow-y: scroll;
}

.quotes .q p::-webkit-scrollbar {
  display: none;
}

.quotes .q > div {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quotes .q > div span {
  font-size: 0.8em;
}

.quotes .q > div img {
  width: 20px;
  height: 20px;
  filter: invert(100%);
  cursor: pointer;
}

.quote-generator > button {
  margin-top: 20px;
  width: 100%;
  cursor: pointer;
  padding: 10px 0;
  border-radius: 5px;
  border: none;
  font-size: 1em;
  background: linear-gradient(to right, #1d7efd, #8f6fff);
  color: #fff;
}


Creating the Components

Within the src directory of your project, organize your files by creating a “components” folder. Inside the components folder, create the following files:
  1. QuoteGenerator.jsx

Adding the Codes

Add the respective code to each newly created file to define the layout and functionality of your chatbot.

In src/QuoteGenerator.jsx, add the code.


import React, { useEffect, useState } from "react";
import copy from "./assets/copy.png";

const QuoteGenerator = () => {
  const [quotes, setQuotes] = useState([]);
  const [quote, setQuote] = useState("");
  const [author, setAuthor] = useState("");
  const [isReady, setIsReady] = useState(false);

  //Handle Fetch Quote Function
  const fetchQuote = async () => {
    setIsReady(false);
    try {
      const url = await fetch(
        "https://api.api-ninjas.com/v1/quotes/?X-Api-Key=Gr3u7UZY9JuGrSUKmMnHqg==yPloDwgeiiMYYrDx"
      );
      const response = await url.json();
      setQuotes((q) => {
        // Add the new data at the beginning of the array
        const updatedArray = [response[0], ...q];

        // Check if the array length exceeds 4
        if (updatedArray.length > 4) {
          // Remove the last item
          updatedArray.pop();
        }

        return updatedArray;
      });
      setQuote(response[0].quote);
      setAuthor(response[0].author);
      setIsReady(true);
    } catch (err) {
      console.log("Error fetching data:", err);
    }
  };

  //Fetch Quote immediately component is mounted
  useEffect(() => {
    fetchQuote();
  }, []);

  //Handle Copy Function
  const handleCopy = (e) => {
    const text =
      e.target.parentElement.parentElement.querySelector("p").textContent;
    navigator.clipboard.writeText(text);
    return alert("Copied");
  };

  return (
    <div className="quote-generator">
      <h1>Quote Generator</h1>
      {isReady ? (
        <div className="quote">
          <p>{quote}</p>
          <div>
            <button onClick={(e) => handleCopy(e)}>copy</button>
            <span>{author}</span>
          </div>
        </div>
      ) : (
        <p className="pre-message">Loading Quote...</p>
      )}

      {quotes && (
        <div className="quotes">
          {quotes.map((v, i) => (
            <div key={i} className="q">
              <p>{v.quote}</p>
              <div>
                <img onClick={(e) => handleCopy(e)} src={copy} />
                <span>{v.author}</span>
              </div>
            </div>
          ))}
        </div>
      )}
      <button onClick={fetchQuote}>Generate Quote</button>
    </div>
  );
};

export default QuoteGenerator;


In App.jsx, add the code.

import React from "react";
import QuoteGenerator from "./QuoteGenerator";

const App = () => {
  return <QuoteGenerator />;
};

export default App;

Conclusion and Final word

Now, we have reached the end of our code, for any information, you can comment any problem or code-not-working issues to resolve it, am always with you. You can also visit my YouTube Channel for more updates on HTML, CSS & JavaScript Designs. I believe you can create "Build A Random Quote Generator In React JS | React Project For Beginners". and do so much more with codes. Go extremely far in exploring the world of HTML, CSS & JavaScript, its gonna be fun, trust me 😃.

Keep experimenting! You can add other cool features. Try improving error handling and adding other cool updates to make your chatbot even better.

If you run into any issues, you can download the source code for this AI chatbot project by clicking the “Download” button. Don’t forget to check the README.md file for setup and usage instructions. If you need help, you’ll also find support information there.

Happy Coding Journey 🚀




Post a Comment

0 Comments

Close Menu