Search code examples
reactjseventsaddeventlistenerflash-message

How do I add an event listener to a React component?


I'm trying to build a React web app (v 16.13.0). I want a flash message component, to display status after a form is submitted. If there is already something standard, that would be preferable, but since I can't find anything, I'm trying to roll my own using this -- https://medium.com/@jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53 . Here's the component

import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';

import './index.css';

export const Flash = () => {
    let [visibility, setVisibility] = useState(false);
    let [message, setMessage] = useState('');
    let [type, setType] = useState('');

    useEffect(() => {
        Bus.addListener('flash', ({message, type}) => {
            setVisibility(true);
            setMessage(message);
            setType(type);
            setTimeout(() => {
                setVisibility(false);
            }, 4000);
        });


    }, []);

    useEffect(() => {
        if(document.querySelector('.close') !== null) {
            document.
            querySelector('.close').
            addEventListener('click', () => setVisibility(false));
        }
    })

    return (
        visibility && <div className={`alert alert-${type}`}>
                <span className="close"><strong>X</strong></span>
                <p>{message}</p>
            </div>
    )
}

Problem is, web site uses custom code, but doesn't show source for

        Bus.addListener('flash', ({message, type}) => {
            setVisibility(true);
            setMessage(message);
            setType(type);
            setTimeout(() => {
                setVisibility(false);
            }, 4000);
        });

so my question is, how do I add an event listener to a React component?

Edit: In response to the answer given, I created this file ...

localhost:client davea$ cat src/Utils/Bus.js 
import EventEmitter from 'events';
export default new EventEmitter();

but re-compiling my module results in this error ...

./src/components/Flash/index.js
Module not found: Can't resolve '../Utils/Bus' in '/Users/davea/Documents/workspace/chicommons/maps/client/src/components/Flash'

These are the first lines of the file above. Note the second "import" where I'm importing "Bus" ...

import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';

import './index.css';

export const Flash = () => {

Solution

  • The website included the code: https://medium.com/@jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53

    To set that up, we need to create a new folder in our root directory and name it Utils and create on it a Bus.js file with will contains the following code:
    
    import EventEmitter from 'events';
    export default new EventEmitter();
    

    This is all Bus.js is, a simple event emitter.

    You can also use react-toastify or useToasts for this.