Add dynamic event listners in React

Viewed 34

Is there any way where I can add dynamic eventlistners, which will be triggered for specific urls and it can detect which events are called on that specific url?

For ex - My react apps have multiple routes and out of those routes for specefic routes I want to see which actions (by actions I mean button click, keypress etc) are executing and based on that I want to call an API with the action that is being called.

1 Answers

Yes – add an event listener in an useEffect (and clean it in the effect cleanup function) in that route's component:

function MyView() {
  React.useEffect(() => {
    const handler = e => console.log(e);
    window.addEventListener('click', handler);
    return () => window.removeEventListener('click', handler);
  }, []);
  return <>Hello!</>;
}

// Not shown: hooking MyView up to your router.

You can also use a premade event hook such as react-use's 'useEvent'.

Related