![]() |
VOOZH | about |
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.
Let us take a look at how the final feature will look like:
Prerequisite: The pre-requisites for this project are:
Approach: The "Joke" 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 which on click generates a joke. 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. The prop is fetching the Joke from API whenever the code is being fetched.
Steps to create the application:
Step 1: Initialize the project from terminal using the command.
npm create vite@latest jokegenerator --template reactStep 2: Navigate to the project folder using the command.
cd jokegeneratorStep 3: Create a folder called components and add two files in it Button.js and Joke.js
Example: Write the following code in respective files.
Steps to run the application:
Step 1: Type the following command in terminal of your project directory
npm run devStep 2: Type the following URL in your web browser.
http://localhost:5173/Output: