Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 336
user3213604 Avatar asked May 30 '17 19:05

user3213604


People also ask

How do you list all event listeners?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

What is SyntheticEvent in React?

Overview. Your event handlers will be passed instances of SyntheticEvent , a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers.

How do I use onMouseOver in React?

We do this by adding onMouseOver to the button element. After declaring that this element has an onMouseEnter event handler, we can choose what function we want to trigger when the cursor hovers over the element. We declare a function called changeBackground above the view part of the 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.

like image 60
Dylan Kerler Avatar answered Oct 12 '22 23:10

Dylan Kerler