preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.01k stars 156 forks source link

Match fails on the first render when using hashHistory #415

Open sebasjm opened 2 years ago

sebasjm commented 2 years ago

Using <Match /> before <Route history={createHashHistory()} /> will try to match non-hash history so the <Router /> component must be rendered before using match.

Also <Link /> activeClassName is affected

Repository https://github.com/sebasjm/preact-router-match-history-issue To reproduce, go to profile and refresh the page. The upper header will take the path as / but the lower header will take the correct one.

Using preact-router@3.2.1

Maybe exporting an init function to set this customHistory before rendering? https://github.com/preactjs/preact-router/blob/main/src/index.js#L14

import Router from 'preact-router';
import Match from 'preact-router/match';

// this will fail
// when rendering https://host/path#/subpath it will take /path
render(
  <div>
    <Match>{({ path }) => <pre>{path}</pre>}</Match>
    <Router history={createHashHistory()}>
      <div default>demo fallback route</div>
    </Router>
  </div>
);

// this will match correctly
// when rendering https://host/path#/subpath it will take /subpath
const customHistory = createHashHistory()
render(
  <div>
    <Router history={customHistory} />
    <Match>{({ path }) => <pre>{path}</pre>}</Match>
    <Router history={customHistory}>
      <div default>demo fallback route</div>
    </Router>
  </div>
);
enricozb commented 1 year ago

Indeed still a bug with v4.1.2, the fix still works as well.