Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically navigate with preact-router?

I'm trying to figure out how to structure the frontend part of a web application using typescript, preact and preact-router. I've come a long way but I still need to figure out how to programmatically navigate (redirect) with preact-router. I can do history.replaceState(null, null, '/#/redirectedUrl');, but while that changes the URL in the location bar, preact-router doesn't route to the new URL.

What is the preferred way to programmatically navigate when using preact-router?

like image 614
David Nordvall Avatar asked Mar 09 '17 21:03

David Nordvall


2 Answers

Importing the function route from 'preact-router' is the way to go:

import { route } from 'preact-router';
route('/url/to/rout/to');
like image 190
David Nordvall Avatar answered Oct 26 '22 18:10

David Nordvall


You can do it in two ways based on your need

import { route } from 'preact-router';
route('url');

This will create a pushState in the history (i.e.,) it will create a new entry for this url

import { route } from 'preact-router';
route('url', true);

This will create a replaceState in the history (i.e.,) this will replace the current page url entry in the history with the url you will be routing to. You can make use of this in cases like, when routing from login screen to your home/dashbaord screen, where on click of browser back button, you don't want user to go back to login screen once the user has been logged in (thus replacing the login entry with your dashbaord entry).

like image 36
Kowsalya Avatar answered Oct 26 '22 17:10

Kowsalya