10

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
David Nordvall
  • 12,404
  • 6
  • 32
  • 52

2 Answers2

11

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

import { route } from 'preact-router';
route('/url/to/rout/to');
David Nordvall
  • 12,404
  • 6
  • 32
  • 52
  • You were pretty close with your original approach too actually, just `replaceState()` amends the current history entry instead of adding a new one, so preact-router can't see it (amending doesn't fire events). You can do this though: `history.pushState(null, null, '/#/redirectedUrl')` – Jason Miller Mar 16 '17 at 00:26
  • 1
    @JasonMiller actually I can't get preact-router to route even when using `history.pushState(null, null, '/#/url');`. Could it be a matter of timing/where I'm making the call from? I'm currently making this call in my component's `render()`-method. – David Nordvall Mar 16 '17 at 09:15
  • Now I realize I sortof steered you astray there - `pushState()` also doesn't fire any events, so the router won't respond to that either. The `location.hash` assignment you went with is probably best, or if you want to keep things abstracted you can import the `route` function from `preact-router` and call `route('/url')`. – Jason Miller Mar 16 '17 at 18:24
  • Yes, that'll nicely abstract which history I am using. I'll update my answer. – David Nordvall Mar 18 '17 at 20:26
3

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).

Kowsalya
  • 1,378
  • 16
  • 25