DEV Community

Ion Prodan
Ion Prodan

Posted on • Originally published at yon.fun on

StencilJS Router Events

If you would take a look to Stencil Router documentation, you wouldn't find any info about open nor close page events, so how we would listen to them? I made a simple library for this scope.

Let's say we have an application compiled by Stencil which contains more than one page. Now, we would like to add Google Analytics on our pages. Let's see how we can implement this purpose.

Here's a standard stencil router configuration:

StencilJS Router Events

Nothing special, we just provide some props to a stencil-route component, in order to dynamically generate our app-home and app-about components based on History links. More about how to set up a stencil router, check this article.

Now let's install ip-stencil-route-listener library and make some changes:

npm i ip-stencil-route-listener
Enter fullscreen mode Exit fullscreen mode

After installing, we have to add <ip-stencil-route-listener /> component inside of routeRender function of <stencil-riuter />. Take a look to red lines:

StencilJS Router Events

Nothing much! Now each time when you'll enter or leave a page, the EventListener will trigger pageEnter or pageLeave events. The names of these events talk about their selves.

Take a look at this image:

StencilJS Router Events

So, let's add Google Analytics on pageEnter event:

  @Listen('pageEnter')
  onPageEnter(e: CustomEvent<LocationSegments>) {
    // This is a Goolge Analytics event
    ga('send', 'pageview', e.detail.pathname);
  }
Enter fullscreen mode Exit fullscreen mode

Here is an example of this demo.

Consider using this library until there will be some official events support delegated by stencil router. I reckon they will implement kind of these events very soon.

Top comments (3)

Collapse
 
mariospas profile image
Marios Passaris

Thanks for your component. I used it and it is working fine when I run npm start but when I build my project by running npm run build and then run serve www/ the events are not working. Do you have any ideas why ?

Collapse
 
davidfrahm profile image
David Frahm

...or maybe the Stencil team won't be adding events:

github.com/ionic-team/stencil-rout...

Collapse
 
wanoo21 profile image
Ion Prodan

Yes, unfortunately they won't, maybe it's time to improve this little plugin.