Joke Generator Using React and Joke API
Joke Generator Using React and Joke API
Overview
This is a simple Joke Generator application built using React. It fetches programming-related jokes from the JokeAPI and displays them on the screen. The app consists of three main components:
- App.js - The root component.
- Joke.js - Fetches and displays a joke.
- Button.js - A button to fetch a new joke.
Project Structure
/joke-generator
│── /src
│ ├── App.js
│ ├── Joke.js
│ ├── /components
│ │ ├── Button.js
│ ├── /styles
│ │ ├── Joke.css
│ │ ├── Button.css
│ ├── index.js
│── package.json
│── README.md
Installation
Clone the repository:
git clone https://github.com/brahmaputraS/react-project.git
Navigate to the project folder:
cd joke-generator
Install dependencies:
npm install
Start the development server:
npm start
Components
1. App.js
This is the main component of the app. It renders the heading and includes the Joke component.
import Joke from "./Joke";
import './Joke.css';
function App() {
return (
<div className="App">
<h1>Joke Generator Using React and Joke API</h1>
<Joke/>
</div>
);
}
export default App;
2. Joke.js
This component fetches a joke from the JokeAPI and displays it. It includes a button to fetch new jokes.
import React from "react";
import Button from "./components/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} />
<br/>
<p>{joke}</p>
</div>
);
}
export default Joke;
3. Button.js
A simple button component that triggers the fetchApi function.
import React from "react";
import './Button.css';
const Button = (props) => {
return <button onClick={props.callApi}>
Click to generate a joke.
</button>;
}
export default Button;
Styling
Create Joke.css and Button.css for styling the components.
Joke.css
.joke {
text-align: center;
margin-top: 20px;
font-size: 1.2rem;
}
Button.css
button {
padding: 10px 20px;
font-size: 1rem;
background-color: #008cba;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #005f73;
}
API Used
JokeAPI - Fetches programming-related jokes.
- Endpoint: https://sv443.net/jokeapi/v2/joke/Programming?type=single
- Response Example:
{
"error": false,
"category": "Programming",
"type": "single",
"joke": "Why do programmers prefer dark mode? Because light attracts bugs!"
}
Screenshot
Conclusion
This project demonstrates how to use React with an external API to build a simple yet functional joke generator. You can extend the app by adding categories, enhancing UI, or storing favorite jokes.