preactpreact-router

Programmatically route with wmr / preact-iso?


I've been playing with wmr and preact-iso and coming from preact-cli, preact-router, etc, I'm a bit confused on how to do some of the things I used to be able to do.

Case in point: preact-router's route() function seems to be missing from preact-iso's router package.

How would I route from code?

I used to be able to do this:

import { route } from 'preact-router';

// Send the user to /path
route('/path');

So how would I do that with WMR / preact-iso?

And somewhat related: Is there any way I can use the <Link /> component with preact-iso?


Solution

  • route() exists upon the useLocation hook.

    import { useLocation } from 'preact-iso';
    
    const location = useLocation();
    
    location.route('/error');
    

    Edit: Missed your question about <Link>. You can create this yourself, we don't ship an equivalent. It's just a shallow wrapper around an anchor tag.

    Here's a pretty direct copy:

    function Link({
        class: c,
        className,
        activeClass,
        activeClassName,
        ...props
    }) {
        const inactive = [c, className].filter(Boolean).join(' ');
        const active = [c, className, activeClass, activeClassName].filter(Boolean).join(' ');
        const matches = useLocation().url === props.href;
    
        return <a { ...props } class={matches ? active : inactive} />;
    }