React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a quote of the day app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app quote-of-the-day
with NPM to create our React project.
Create the Quote of the Day App
To create the quote of the app, we write:
import React, { useEffect, useState } from "react";
export default function App() {
const [quoteOfTheDay, setQuoteOfTheDay] = useState("");
const [quotes, setQuotes] = useState([]);
const getQuotes = async () => {
const res = await fetch(`https://type.fit/api/quotes`);
const quotes = await res.json();
setQuotes(quotes);
};
const getRandomQuote = () => {
const index = Math.floor(Math.random() * quotes.length);
setQuoteOfTheDay(quotes[index].text);
};
useEffect(() => {
getQuotes();
}, []);
return (
<div className="App">
<button onClick={getRandomQuote}>get quote</button>
<p>{quoteOfTheDay}</p>
</div>
);
}
We have the quoteOfTheDay
string state and the quotes
day created with the useState
hook.
Then we add the getQuotes
function which makes a GET request to an API to get a list of quotes.
We call res.json
to return a promise with the quotes JSON.
Then we call setQuotes
to set the quotes
state.
The getRandomQuote
function gets a random index with Math.random
and Math.floor
to round the decimal number down to the nearest integer.
Then we call setQuoteOfTheDay
to set the quote to the string text
property.
We have the useEffect
callback to call getQuotes
to get the quotes.
The 2nd argument is an empty array so it only runs when App
mounts.
Then we return JSX with a button with the onClick
prop set to getRandomQuote
.
We run getRandomQuote
when we click on the button.
And below that, we show the quoteOfTheDay
.
Conclusion
We can create a quote of the day app easily with React and JavaScript.