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 random joke 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 random-joke
with NPM to create our React project.
Create the Rando Joke App
To create the random joke app, we write:
import { useEffect, useState } from "react";
export default function App() {
const [joke, setJoke] = useState("");
const getJoke = async () => {
const res = await fetch("https://api.chucknorris.io/jokes/random");
const { value } = await res.json();
setJoke(value);
};
useEffect(() => {
getJoke();
}, []);
return (
<div className="App">
<p>{joke}</p>
<button onClick={getJoke}>get new joke</button>
</div>
);
}
We have the joke
state, which is a string state created by useState
.
Then we add the getJoke
function to make an HTTP request to the Chuck Norris jokes API with fetch
.
We make a GET request and call res.json()
to return a promise with the data object.
Then we call setJoke
to set the joke
value.
We call getJoke
with the useEffect
callback to load the joke when we load the component.
The callback only runs when we mount it because we pass in an empty array into the 2nd component.
Then we render the joke
string.
And then we add a button that calls getJoke
when we click it.
Conclusion
We can create a random joke app easily with React and JavaScript.