Search code examples
routerpreact

Preact-Router - Handle routes from sub directory


I'm currently creating a SPA that can be included and run from any route.

Currently any <Link /> component I create redirects the client back to the root of the domain it's on plus the intended path.

In react-router there's a property to set a starting base path; basename.

This doesn't seem to be present in preact-router and I'd really rather not switch to react-router as it's significantly larger and I won't be using many of the additional features.

A simple example of the routes:

<Router>
  <Route
    path="/"
    component={Home}
  />
  <Route
    path="/:slug"
    component={Merchant}
  />
</Router>

I've seen a couple of post around the internet implying this is possible but with such little documentation it's a little tricky to piece together.

Any help is much appreciated.

Thanks.


Solution

  • I've ended up wrapping the preact-router Link and Router with my own components. From there I can prefix the path property value with my apps base route, e.g:

    <MyRoute
       path="/"
       component={Home}
    />
    

    Then somewhere within <MyRoute />:

    const route = 'my/app/base/path';
    
    let result = (route || '') + this.props.path;
    
    result = result.replace(/([^:]\/)\/+/g, '$1');
    

    Then render the preact-router default component with the result value, <Route path={result} />