Create a  Random Quotes Genarator with React  and Vite

Create a Random Quotes Genarator with React and Vite

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