Search code examples
javascriptreactjsreact-functional-component

ReactJs functional component add function to an eventListener and then invoke it


Is it possible to create an event listener in a functional component and then invoke it from chrome console?

For example:

const Component = () => {
   const [hook,setHook] = useState();

   const handlerFunction = (arg) => {
      console.log(arg);
   }

   // how to add an event listener?
   return <div>Hello world<div>
}

Solution

  • The simplest solution would be to add a global variable:

    const Component = () => {
        const [ value, setValue ] = useState();
    
        window.MY_GLOBAL_CONTAINER = (arg) => {
            setValue(arg);
            console.log(arg);
        };
    
       return <div>Hello world, { value }</div>
    }
    

    which you can access with:

    MY_GLOBAL_CONTAINER('test')
    

    Probably better to use a ref:

    const Component = () => {
        const [ value, setValue ] = useState();
        const ref = useRef(null);
    
        useEffect(()=>{
            ref.current.handlerFunction = (arg) => {
                setValue(arg);
                console.log(arg);
            };
        },[])
    
        return <div ref={ ref } id="containerElementInsideTheDom">Hello world, { value }</div>
    }
    

    which you can access with:

    document.getElementById('containerElementInsideTheDom').handlerFunction('test')