how to get list of all registered synthetic event handlers/listeners for a React Component?

Viewed 2512
var Rc = <MyReactComponent 
  onChange={(e) => {console.log(e);} 
  onClick={(e) => { workIt(); }} />;

How do I get the list of listeners ['onChange', 'onClick'], for component Rc.

I see questions related to finding listeners on DOM nodes... How to find event listeners on a DOM node using JavaScript; for which apparently no simple call exists like getEventLiteners(), alongside addEventListener() is DOM DOES support.

Is there a clean and easy way to get the listeners for React Component?

1 Answers

There isn't any in-built way to do this in React, however you can create a simple function to do this for you:

// Build a mapping of event listeners
const getListeners = component => {
    return Object.fromEntries(
       Object
           .entries(component.props) // Get the props
           .filter(([key, value]) => key.startsWith("on")) // Filter event listeners
    );
};

const foo = <SomeComponent
    onChange={(e) => {console.log(e);} 
    onClick={(e) => { workIt(); }}
/>;

console.log("listeners", getListeners(foo));
// { onChange: f, onClick: f }

In this case, we filter all props with getListeners that start with "on" because every event listener in React starts with "on".

You could make this more robust by explicitly filtering on the actual supported event listeners in React: https://reactjs.org/docs/events.html#reference And also filtering the value of each prop to make sure it is a function.

Related