Random  Joke Generator using the JokeAPI

Random Joke Generator using the JokeAPI

·

2 min read

A Frontend mentor project about a random advice generator inspired this project. This project taught me how to interact with 3rd-party APIs. This project uses the Joke API to generate random jokes with a Question and punchline.

Prerequisites

Before we start, let's set up a new project using create-react-app. This process is pretty simple.

//Create a new react app
npx create-react-app random-generator
// Move into new project
cd random-generator
// Start the project
npm start

Start the project. You would also need to install Axios. Axios is a popular promise-based HTTP client for the browser and node.js. To install Axios in your React App:

//Using npm
npm install axios
//Using yarn:
yarn add axios

Creating the Joke Generator:

Navigate to the src folder and create a Generator.js file, and add the following code:

import React, { useState, useEffect } from "react";
import axios from "axios";

function Generator() {
  const [generator, setGenerator] = useState([]);
  const fetchAdvice = async () => {
    try {
      const response = await axios("https://v2.jokeapi.dev/joke/Any");
      setGenerator(response.data);
      // console.log(response.data)
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    fetchAdvice();
  }, []);
  return (
    <div className="container">
      <div className="box">
        <h3 className="header">JOKE #{generator.id}</h3>
        <h4 className="text">
          Question: {generator.setup}
        </h4>
        <h4 className="text">Punchline: {generator.delivery}</h4>
        <div className="span">
          <span className="line"></span>
          <div className="rectangle">
            <span className="stopper"></span>
            <span className="stopper"></span>
          </div>
          <span className="line"></span>
        </div>

        <div className="button">
          <div onClick={fetchAdvice}>
            <svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M20 0H4a4.005 4.005 0 0 0-4 4v16a4.005 4.005 0 0 0 4 4h16a4.005 4.005 0 0 0 4-4V4a4.005 4.005 0 0 0-4-4ZM7.5 18a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm0-9a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm4.5 4.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm4.5 4.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Zm0-9a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z"
                fill="#202733"
              />
            </svg>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Generator;

Import Generator.js to your App.js file. Add your preferred CSS styles.

Conclusion

In this tutorial, you have learned how to interact with 3rd-party APIs, using a JokeAPI to generate random jokes(Questions and punchlines).

You can also check out my GitHub for the source code of this tutorial:

https://github.com/Nkwor-Jane/randomn-joke-generator

Resources