Vanilla JS - Native Routing Example

Implementing Native Routing with @beacon.li/bar in Vanilla JS

If you're using the @beacon.li/bar package in a Vanilla JavaScript environment and you want to integrate native routing, you can achieve this by using the Beacon.setRouter method. This method allows you to define custom logic for handling routing events and updating the beacon widget's behavior accordingly.

Setting up the Router

To implement native routing, follow these steps:

  1. Import the Beacon module from the @beacon.li/bar package as you normally would:

    import { Beacon } from '@beacon.li/bar';
  2. Use the Beacon.setRouter method to define your routing logic. This method takes a callback function as its parameter, where you can specify how the Beacon widget should behave based on the current URL:

    Beacon.setRouter(url => {
        // your logic here
    });

Custom Routing Logic

Inside the callback function passed to Beacon.setRouter, you can implement your custom routing logic. Depending on your application's requirements, you may want to:

  • Show or hide the Beacon widget based on the URL.

  • Perform any other actions based on the URL.

Here's a simple example that shows how to conditionally open or close the Beacon widget based on the URL:

Beacon.setRouter(url => {
    if (url === '/contact') {
        Beacon.open(); // Show Beacon widget on the 'contact' page.
    } else {
        Beacon.close(); // Hide Beacon widget on other pages.
    }
});

By setting up the Beacon.setRouter method with your custom routing logic, you can integrate the Beacon widget seamlessly into your application's navigation flow, ensuring a smooth user experience.

Last updated