Create a Random Quotes Genarator with React and Vite

Shivam SharmaShivam Sharma
1 min read

How to create React app?

There are many ways to create a react app but this blog focuses on how to create a React app with Vite. If you want to know about Vite then Check. Make sure you have downloaded the node.js in your system.

Getting started

I hope you have created a React app with Vite and make sure your app is running at localhost. This is a very simple app, you can see the following code and copy it to run into your machine.

import { useState, useEffect } from 'react'
import './App.css'

function getRandomQuote(quotes) {
  return quotes[Math.floor(Math.random() * quotes.length)];
}

function App() {
  const [quotes, setQuotes] = useState([]);
  const [quote, setQuote] = useState(null);

  useEffect(()=>{
    fetch("https://type.fit/api/quotes")
    .then((res) => res.json())
    .then((json) => {
      setQuotes(json)
      setQuote(json[0]);
    });
  }, []);

  function getNewQuote() {
    setQuote(getRandomQuote(quotes));
  }

  return (
    <>
       <main>
        <h1>Quote generator</h1>
        <section>
          <button onClick={getNewQuote}>New Quote</button>
          <h3>
            <span>"</span>
            {quote?.text}
          </h3>
          <i>{quote?.text}</i>
        </section>
       </main>
    </>
  )
}

export default App
5
Subscribe to my newsletter

Read articles from Shivam Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shivam Sharma
Shivam Sharma

I’m an Open-Source enthusiast & Final year pursuing my Bachelors in Computer Science. I am passionate about Kubernetes, Web Development, DevOps & I enjoy learning new things.