How to create a Random Joke using React app through API fetching? - GeeksforGeeks

27 Nov, 2020
In this tutorial, we’ll make a website that fetches data (joke) from an external API and displays it on the screen. We’ll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React for this project, we need not reload the page to display the fetched data.
The “Button” component. The “App” file is a functional component and contains a state variable Joke, which initially set to an empty string, and depending upon the state of the Joke, the output gets rendered. The Component outputs the “Button” component if the Joke contains an empty string or the value of Joke if it is not empty. The “Button” component that is getting rendered is also an imported functional component that outputs a button element. We are also passing some props to the “Button” component, which is a method named callAPI. 
Prerequisite: The pre-requisites for this project are:
React
Function Components
ReactJS AJAX and API
ES6
Reason to Create this app: The purpose of building such a simple website is to get some experience of working with API’s as all of them are more or less the same. The website uses a simple interface where we have a button, when hovered changes color, and when clicked makes a request to some external API and fetches data.
Example: Create a new React project using the command npx create-react-app. In the same directory, we have a file index.js which manages all our components and renders the App component to the screen.
Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively.The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. Button.js:JavascriptJavascript// Import React (Mandatory Step).import React from "react";      // Create a functional component    const Button = (props) => {        return <button onClick={props.callApi}>         Hello Geek!!         </button>;    }  // Export Button Componentexport default Button;
Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively.
The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. 
Button.js:
Javascript
// Import React (Mandatory Step).import React from "react";      // Create a functional component    const Button = (props) => {        return <button onClick={props.callApi}>         Hello Geek!!         </button>;    }  // Export Button Componentexport default Button;
App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags.At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke.We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc.  It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke.The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string.JavascriptJavascript// Import React (Mandatory Step).import React from "react";// Import ReactDOM (Mandatory Step).import ReactDOM from "react-dom";  // Import The Button Component from Button.js import Button from "./Component/Button";  const rootElement = document.getElementById("root");  // Create a functional componentconst App = () => {    // Declare a state variable    const [Joke, setJoke] = React.useState("");      const fetchApi = () => {        // Fetching data from the API            fetch("https://sv443.net/jokeapi/v2/joke/Programming?type=single")            .then((res) => res.json())            .then((data) => setJoke(data.joke));      };      return (        // Return the Button Component with a conditional statement        <div>{Joke === "" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div>      );}  // Rendering the App Component.ReactDOM.render(    <App />,  rootElement);export default App
App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags.
At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke.
We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc.  It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke.
The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string.
Javascript
// Import React (Mandatory Step).import React from "react";// Import ReactDOM (Mandatory Step).import ReactDOM from "react-dom";  // Import The Button Component from Button.js import Button from "./Component/Button";  const rootElement = document.getElementById("root");  // Create a functional componentconst App = () => {    // Declare a state variable    const [Joke, setJoke] = React.useState("");      const fetchApi = () => {        // Fetching data from the API            fetch("https://sv443.net/jokeapi/v2/joke/Programming?type=single")            .then((res) => res.json())            .then((data) => setJoke(data.joke));      };      return (        // Return the Button Component with a conditional statement        <div>{Joke === "" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div>      );}  // Rendering the App Component.ReactDOM.render(    <App />,  rootElement);export default App
Output: Our app is now complete and working, although the app is simple, it helps a lot in understanding how to make API calls in react and manipulate the response received to use it in the app.
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?