React JS - Native Routing Example
Enabling Native Routing with @beacon.li/bar in a React Application
@beacon.li/bar in a React ApplicationIf you're using React along with react-router-dom and you want to enable native routing for the Beacon widget, you can achieve this by integrating the @beacon.li/bar package with your React application. This allows you to control the behavior of the Beacon widget based on the current route using the useEffect hook.
Integrating @beacon.li/bar with React Router
@beacon.li/bar with React RouterHere's how you can enable native routing with beacon in your React application:
Import the necessary modules and hooks at the beginning of your child component:
import { Beacon } from '@beacon.li/bar';
import { useHistory } from 'react-router-dom';
import { useEffect } from 'react';Obtain the
historyobject fromreact-router-domusing theuseHistoryhook:
const history = useHistory();Use the
useEffecthook to set up Beacon's router based on the current route. This allows you to navigate to different routes when the user interacts with the Beacon widget:
useEffect(() => {
Beacon.setRouter(path => {
history.push(path);
});
}, [history]);How It Works
The
useHistoryhook provides you with thehistoryobject, which contains methods for manipulating the browser's history and navigation.In the
useEffecthook, you callBeacon.setRouter(path => history.push(path)). This configures Beacon to use the React Router'shistory.pushmethod when navigating to different routes.Whenever the user interacts with the Beacon widget, it will trigger this router configuration, allowing you to seamlessly integrate beacon into your application's navigation flow.
By following these steps, you can enable native routing for the Beacon widget in your React application, ensuring a consistent and user-friendly experience when users interact with the beacon bar.
Last updated