React Example for Event Listeners in Beacon

In a React application, you can use event listeners from the @beacon.li/bar package to respond to custom events emitted by Beacon Bar and update your component's state based on those events. This allows you to create dynamic and interactive user experiences.

Example: Using an Event Listener to Update State

Here's an example of how to use an event listener to update the state of a React component:

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;

In this example:

  • We initialize a state variable called state using useState. This state will be updated when a specific custom event is triggered.

  • Inside the useEffect hook, we define an event listener function, listener, that checks if the event name matches the custom event you want to respond to.

  • We add the event listener using Beacon.addEventListener(listener).

  • To ensure cleanup when the component unmounts, we return a function that removes the event listener using Beacon.removeEventListener(listener).

  • Finally, we render the component with the state variable to display the current state.

This example demonstrates how to use an event listener from @beacon.li/bar to manipulate the state of a React component in response to specific custom events emitted by Beacon Bar.

Last updated