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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With