In Vue.js we can emit custom events along with a parameter like
this.$emit('bark', 3);
and then we can listen to this event on the parent component like
<parent-component @bark=handleBark />
handleBark (howManyTimes) {
console.log(howManyTimes);
// logs 3
}
How can we do that in React?
addEventListener(eventName, listener); } function unsubscribe(eventName, listener) { document. removeEventListener(eventName, listener); } function publish(eventName, data) { const event = new CustomEvent(eventName, { detail: data }); document. dispatchEvent(event); } export { publish, subscribe, unsubscribe};
To pass data from child to parent component in React: Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .
An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.
We need custom event emitter to do that. This pattern is being used by many well known libraries and a very good example is React Redux. An event emitter is a pattern that listens to a named event, fires a callback, then emits that event with a value. Sometimes this is referred to as event dispatcher or pub/sub model, or listener.
Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc. onClick instead of onclick. onClick= {shoot} instead of onClick="shoot ()".
When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered. When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class.
Our useEffect hook only runs once on component mount, and adds an event listener to the window resize event. The event listener sets our state variable to the new size of the viewport. Finally, we return a function to be called on unmount which will tidy up and remove the event listener.
You just simply pass down the custom event handler as props
.
For example if you have Parent
and Child
functional components. You can then define the custom event handler in the Parent
component like:
function Parent(props) {
const handleBark = (howManyTimes) => {
console.log(howManyTimes);
};
// note below I am sending the handleBark method to Child as props
return (<Child bark={handleBark} />);
}
and then inside the Child
component you can simply call it as:
props.bark(10);
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