Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Nutrition Meter - Calories Tracker App using React
Next article icon

Create a Random Joke using React app through API

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Random Joke using React app through API

Random Joke using React app through API

Prerequisite: The pre-requisites for this project are:

  • React
  • Function Components
  • ReactJS AJAX and API
  • useState

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.

npx create-react-app jokegenerator

Step 2: Navigate to the project folder using the command.

cd jokegenerator

Step 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.

  • App.js: This file imports the components to render it on the web page
  • Joke.js: This file contains the joke to be displayed and makes the API call
  • Joke.css: This file contains the styling of all the elements 
  • Button.js: This file contains the button component which generates the joke on click
  • Button.css: This file contains the styling of button element
CSS
/* Joke.css */  body {     background-color: rgb(47, 97, 80); }  .joke {     width: auto;     height: auto;     margin: auto;     display: flex;     flex-direction: column;     align-items: center;     justify-content: center;     color: beige; }  h1 {     text-align: center;     color: beige; } 
CSS
/* Button.css */  button {     display: inline-block;     padding: 10px 20px;     background-color: #70a03a;     color: #ffffff;     border: none;     font-size: 16px;     cursor: pointer;     border-radius: 8px;     transition: background-color .5s; }  button:hover {     background-color: #c1f590; }  button:active {     background-color: #297910; } 
JavaScript
// App.js  import Joke from "./components/Joke";  function App() {     return (         <div className="App">             <h1>Joke Generator Using React and Joke API</h1>             <Joke/>         </div>     ); }  export default App; 
JavaScript
// Joke.js  import React from "react";   import Button from "./Button"; import './Joke.css';  const Joke = () => {     const [Joke, setJoke] = React.useState("");      const fetchApi = () => {         fetch("https://sv443.net/jokeapi/v2/joke/Programming?type=single")             .then((res) => res.json())             .then((data) => setJoke(data.joke));     };      return (         <div className="joke">             <Button callApi={fetchApi} />              <p>{Joke}</p>             </div>     ); }  export default Joke; 
JavaScript
// Button.js  import React from "react"; import './Button.css'  const Button = (props) => {     return <button onClick={props.callApi}>         Click to generate a joke.     </button>; }  // Export Button Component export default Button; 

Steps to run the application:

Step 1: Type the following command in terminal of your project directory

npm start

Step 2: Type the following URL in your web browser.

http://localhost:3000/

Output:

gfg

Next Article
Nutrition Meter - Calories Tracker App using React

P

pushpendrayadav1057
Improve
Article Tags :
  • Project
  • ReactJS
  • Web Technologies
  • ReactJS-Projects
  • Web Development Projects

Similar Reads

  • BMI Calculator Using React
    In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese. Output Previ
    3 min read
  • Create Rock Paper Scissor Game using ReactJS
    In this article, we will create Rock, Paper, Scissors game using ReactJS. This project basically implements class components and manages the state accordingly. The player uses a particular option from Rock, Paper, or Scissors and then Computer chooses an option randomly. The logic of scoring and win
    6 min read
  • Create a Form using React JS
    Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
    5 min read
  • Create a Random Joke using React app through API
    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 f
    3 min read
  • Nutrition Meter - Calories Tracker App using React
    GeeksforGeeks Nutrition Meter application allows users to input the name of a food item or dish they have consumed, along with details on proteins, calories, fat, carbs, etc. Users can then keep track of their calorie intake and receive a warning message if their calorie limit is exceeded. The logic
    9 min read
  • Currency converter app using ReactJS
    In this article, we will be building a very simple currency converter app with the help of an API. Our app contains three sections, one for taking the user input and storing it inside a state variable, a menu where users can change the units of conversion, and finally, a display section where we dis
    4 min read
  • Lap Memory Stopwatch using React
    Stopwatch is an application which helps to track time in hours, minutes, seconds, and milliseconds. This application implements all the basic operations of a stopwatch such as start, pause and reset button. It has an additional feature using which we can keep a record of laps which is useful when we
    5 min read
  • Typing Speed Tester using React
    In this article, we will create a Typing Speed Tester that provides a random paragraph for the user to type as accurately and quickly as possible within a fixed time limit of one minute. This application also displays the time remaining, counts mistakes calculates the words per minute and characters
    9 min read
  • Number Format Converter using React
    In this article, we will create Number Format Converter, that provides various features for users like to conversion between decimal, binary, octal and hexadecimal representations. Using functional components and state management, this program enables users to input a number and perform a range of c
    7 min read
  • Create a Password Validator using ReactJS
    Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. We will use the validator module to achieve this functionality. We will call the isStrongPassword function and pass the conditions a
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences