Custom Event in React Js
- Get link
- X
- Other Apps
Custom Event in React Js
In React, you can create a custom event using the CustomEvent
constructor provided by the browser's built-in window
object, and then dispatch the event using the dispatchEvent()
method.
Here's an example of how to create and dispatch a custom event in a React functional component:
import React, { useRef } from 'react'; function CustomEventExample() { const buttonRef = useRef(null); const handleButtonClick = () => { const customEvent = new CustomEvent('myEvent', { detail: { message: 'Hello world!' } }); buttonRef.current.dispatchEvent(customEvent); }; return ( <div> <button onClick={handleButtonClick}>Dispatch custom event</button> <div ref={buttonRef}></div> </div> ); }
In this example, we create a new CustomEvent
object with the name 'myEvent'
and a detail object containing a message. We then dispatch the event on a button
element using the dispatchEvent()
method.
Note that we need to use a ref
to access the button
element so we can dispatch the event on it. We also need to define a handler function handleButtonClick
that creates and dispatches the custom event.
To listen for the custom event in another part of your application, you can use the addEventListener()
method on the target element:
import React, { useEffect } from 'react'; function CustomEventListener() { useEffect(() => { const button = document.querySelector('button'); button.addEventListener('myEvent', handleCustomEvent); return () => { button.removeEventListener('myEvent', handleCustomEvent); }; }, []); const handleCustomEvent = (event) => { console.log('Custom event received:', event.detail.message); }; return ( <div> <button>Click me to trigger custom event</button> </div> ); }
In this example, we use the useEffect()
hook to add and remove a listener for the 'myEvent'
event on the button
element. When the event is received, we log the message from the event detail to the console.
Note that we need to define the handleCustomEvent
function before adding the listener in useEffect()
. We also use the useEffect()
cleanup function to remove the listener when the component unmounts to avoid memory leaks.
- Get link
- X
- Other Apps
Comments