Implementing Random Joke Generator Project

Step-by-Step Guide on Building the App

Now it’s time to build! In this module, you’ll walk through setting up the project environment, organizing your files, and writing clean, working code for each part of your app. You’ll see how all the pieces come together, from layout to logic.

Set up the environment

  1. Install Node.js: Download and install the LTS version of Node.js from nodejs.org. Verify installation by running node -v and npm -v in a terminal.

  1. Create project folder: Make a new directory (e.g., random-joke-generator) and open it in your code editor.
  2. Initialize npm (optional): In the project folder, run npm init -y if you plan to manage packages.
  3. Open a local server: You can use a live-server extension or npx serve to serve your files locally for testing.

Create Application Structure (Directory Structure)

Organize your project files. For example:

random-joke-generator/

├── public/

│   └── index.html         # HTML template

├── src/

│   ├── components/

│   │   ├── Joke.js        # Component that fetches and displays a joke

│   │   └── Button.js      # Button component to trigger a joke fetch

│   ├── App.js             # Main app component (renders <Joke />)

│   ├── index.js           # Entry point (renders App into DOM)

│   ├── App.css            # Global styles

│   └── index.css          # Default styles

├── package.json           # npm dependencies and scripts

└── README.md

  • App.js – The root React component that imports and renders the Joke component inside a heading.
  • components/Joke.js – Defines the Joke component which holds the joke text in state and fetches from the API.
  • components/Button.js – A reusable button that accepts a prop function to call when clicked.
  • CSS files – (Optional) Styles for layout (e.g. centering the joke text and styling the button). The GeeksforGeeks example used simple CSS to center content and style the button.
  • index.html: Main HTML file with a <div id="root"></div> where React will mount.

This structure keeps logic separate: Joke.js handles data fetching and state, while Button.js is a generic button component. The App.js file ties everything together. Inside index.html, we’ll load React and our scripts.

Steps Needed For The Project

Step 1: Create index.html. In your project folder, make an index.html file with the following skeleton:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Random Joke Generator</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div id="root"></div>
    <!-- Include React and ReactDOM from a CDN -->
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <!-- Babel (for JSX) -->
    <script src="https://unpkg.com/babel-standalone"></script>
    <!-- Our React code -->
    <script type="text/babel" src="./src/App.js"></script>
  </body>
</html>

This file sets up a root element (<div id="root">) and loads React. We include Babel to compile JSX in the browser for simplicity.

Step 2:

Open the src/ folder and there you will find App.js file. Replace the default content with a simple container that renders our joke component. For example:

// src/App.js
import React from "react";
import Joke from "./components/Joke";
import './App.css';


function App() {
    return (
        <div className="App">
            <h1>Random Joke Generator</h1>
            <Joke />
        </div>
    );

This component displays a title and includes the Joke component. (Note: If using modules instead of CDN, you would import React and ReactDOM, but with the above setup we use global ReactDOM.)

Step 3:

In the src/ folder, create another folder named components/. Within that folder, create a Joke.js file and paste the content below into it.

// src/Joke.js
import React, { useState } from "react";
import Button from "./Button";

const Joke = () => {
    const [jokeText, setJokeText] = useState("");
    const fetchJoke = () => {
        // Call the JokeAPI (programming category, single joke)
        fetch("https://v2.jokeapi.dev/joke/Programming?type=single")
          .then(res => res.json())
          .then(data => setJokeText(data.joke));
    };

    return (
        <div className="joke-container">
            <Button callApi={fetchJoke} />
            <p>{jokeText}</p>
        </div>
    );
};

export default Joke;

This component uses React’s useState hook to store the jokeText. The fetchJoke function calls the JokeAPI endpoint and updates the state with data.joke from the JSON response.

The JSX renders our Button and a paragraph showing the current joke. This follows the GFG example’s pattern of calling fetch on click and setting state.

Step 4:

Similarly, create another file called Button.js. In src/components/Button.js, write:

import React from "react";

const Button = (props) => {
    return (
        <button onClick={props.callApi}>
            Generate New Joke
        </button>
    );
};

export default Button;

This is a simple functional component: it renders a <button> that calls the callApi function passed in via props when clicked. In our Joke component, we passed fetchJoke as that prop, so clicking the button will trigger the API call

You can create Joke.css and Button.css for any needed styles. For instance, center the content and add some padding. The tutorial example used a dark green background and centered text. This step is optional; the core functionality works without styling.

Step: 5 CSS Styling (Paste in App.css)

Create a file called App.css in the main folder of random-joke-generator. Paste the below content:

/* App.css */
body {
  margin: 0;
  padding: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #f3f4f6; /* light gray */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.App {
  text-align: center;
  background-color: white;
  padding: 40px 30px;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
}
h1 {
  font-size: 2rem;
  color: #111827;
  margin-bottom: 20px;
}
.joke-container p {
  font-size: 1.2rem;
  color: #374151;
  margin-top: 20px;
  line-height: 1.5;
  word-break: break-word;
}
button {
  background-color: #4f46e5; /* Indigo */
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.3s ease;
}
button:hover {
  background-color: #4338ca;
}
@media (max-width: 480px) {
  .App {
    padding: 30px 20px;
  }
  h1 {
    font-size: 1.5rem;
  }
  .joke-container p {
    font-size: 1rem;
  }
}

Link it with App.js:

If you're using App.css, just import it at the top of your App.js by simply pasting the below line in your App.js file.

import './App.css';

Step 6: Run and Test Locally

In the command prompt, run:

npm start

This starts the React development server and opens http://localhost:3000/. Each time you click the “Generate New Joke” button, the app fetches a random programming joke and displays it. No page reload is needed thanks to React’s state updates. You should see the interface like the screenshot below, where new jokes appear dynamically.