Below is an example of a React component named RandomJoke that displays a random joke in a highlighted text area. Each time the "Next Joke" button is clicked, it updates with a new joke from the list.
jsx
import React, { useState, useEffect } from 'react';
function RandomJoke() {
// Array of jokes
const jokes = [
"Why did the coffee file a police report? Because it got mugged!",
"I'm reading a book about anti-gravity. It's impossible to put down!",
"Did you hear about the mathematician who’s afraid of negative numbers? He'll stop at nothing to avoid them!",
"What do you call fake spaghetti? An impasta!",
"Why don’t scientists trust atoms? Because they make up everything!"
];
// State to store the current joke
const [joke, setJoke] = useState('');
// Function to pick a random joke from the array
const getRandomJoke = () => {
const randomIndex = Math.floor(Math.random() * jokes.length);
setJoke(jokes[randomIndex]);
};
// Load a random joke when the component mounts
useEffect(() => {
getRandomJoke();
}, []);
return (
<div style={{ textAlign: 'center', marginTop: '2rem' }}>
<p
style={{
backgroundColor: '#fff3cd',
color: '#856404',
padding: '20px',
borderRadius: '8px',
fontSize: '1.2rem',
fontWeight: 'bold',
display: 'inline-block'
}}
>
{joke}
</p>
<br />
<button
onClick={getRandomJoke}
style={{
marginTop: '1rem',
padding: '10px 20px',
fontSize: '1rem',
cursor: 'pointer'
}}
>
Next Joke
</button>
</div>
);
}
export default RandomJoke;
Explanation
Joke Array: We define an array of jokes that the component can display.
State: We use the useState hook to store the current joke.
getRandomJoke Function: This function picks a random index from the jokes array and updates the state.
useEffect: When the component mounts, it automatically loads a random joke.
Styling: The joke's paragraph is styled with a highlighted background and rounded borders. Adjust the styles as you see fit.
To use this component, simply import and include it in your application, for example:
jsx
import React from 'react';
import ReactDOM from 'react-dom';
import RandomJoke from './RandomJoke';
function App() {
return (
<div>
<h1>Random Joke Generator</h1>
<RandomJoke />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));