React Example for Event Listeners in Beacon
Example: Using an Event Listener to Update State
import { Beacon } from '@beacon.li/bar';
import { useEffect, useState } from 'react';
function Component() {
// Initialize a state variable
const [state, setState] = useState(false);
useEffect(() => {
// Define an event listener function
const listener = (eventName, attributes, userId) => {
// Check if the event name matches your criteria
if (eventName === 'custom_event_name') {
// Update the state when the custom event is triggered
setState(true);
}
};
// Add the event listener
Beacon.addEventListener(listener);
// Clean up by removing the event listener when the component unmounts
return () => {
Beacon.removeEventListener(listener);
};
}, [setState]);
// Render your component with the state
return (
<div>
<p>State: {state ? 'True' : 'False'}</p>
</div>
);
}
export default Component;
Last updated