I'm trying to figure out how to structure the frontend part of a web application using typescript, preact and preact-router. I've e 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?
I'm trying to figure out how to structure the frontend part of a web application using typescript, preact and preact-router. I've e 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?
Share Improve this question edited Jan 22, 2019 at 5:58 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked Mar 9, 2017 at 21:32 David NordvallDavid Nordvall 13.2k8 gold badges35 silver badges55 bronze badges2 Answers
Reset to default 14Importing the function route
from 'preact-router'
is the way to go:
import { route } from 'preact-router';
route('/url/to/rout/to');
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).