DEV Community

Dhairya Shah
Dhairya Shah

Posted on

Random Joke Fetching in React

Hello 👋,

Today, you will learn to fetch random joke from a node module in React JS

Let's get started,

Create React App

npx create-react-app joke-boi

Install this node module

npm i one-liner-joke

Now create App.js

import React from "react";
import Joke from './Joke'

class App extends React.Component{
  render(){
    return(
      <div>
        <Joke/>
      </div>
    )
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now we'll create a component called Joke in Joke.js

import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import './Joke.css';
import {Card} from 'react-bootstrap'
const oneLinerJoke = require('one-liner-joke');



class Joke extends React.Component{
    componentDidMount() {
        window.addEventListener('load', this.handleGet);
     }

     componentWillUnmount() { 
       window.removeEventListener('load', this.handleGet)  
     }
    handleGet(){
        const getRandomJoke = oneLinerJoke.getRandomJoke();
        document.getElementById('joke').innerText = getRandomJoke.body;
    }
    render(){
        return(
            <div className="container">
                {/* <input type="text" className="form-control" id="joke" disabled/>                 */}

                <Card>
                    <Card.Body>
                    <h2 id="joke">Try refreshing the page if you can't find the joke. Note: It is not a joke</h2><br /><hr />
                       <button className="btn btn-info nextBtn" onClick={this.handleGet}>Don't click here for next joke 😑</button>
                    </Card.Body>
                </Card>
            </div>
        )
    }
}

export default Joke;
Enter fullscreen mode Exit fullscreen mode

And all set! now you can run in console

npm start

Check out GitHub Repository and fork

Joke App in React JS

Happy Coding!

Top comments (0)