Using react-router with reconcilers such as react-three-fiber

Viewed 600

I'm try to use react-router with react-three-fiber. The issue is the <Switch> components lose their context when added inside a react-three-fiber <Canvas> element. To fix this I can wrap the switch inside a <Router> inside the Canvas. And the routes work as expected when manually typing the url. However, the ` elements now seem to reference another Router and don't work when clicked.

Is there a way to make the elements inside and outside the <Canvas> reference the same router?

https://codesandbox.io/s/reach-router-starter-v1-9qcjc

const App = ({ router }) => {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Canvas>
          <Plane color="black" position={[-5, 0, 0]} />
          <Router>
            <Switch>
              <Route exact path="/">
                <Home />
              </Route>
              <Route path="/about">
                <About />
              </Route>
              <Route path="/dashboard">
                <Dashboard />
              </Route>
            </Switch>
          </Router>
        </Canvas>
      </div>
    </Router>
  );
};

const Home = () => <Plane color="red" position={[0, 0, 0]} />;
const About = () => <Plane color="green" position={[0, 0, 0]} />;
const Dashboard = () => <Plane color="blue" position={[0, 0, 0]} />;
1 Answers

You can use npm i wouter instead of react-router-dom https://www.npmjs.com/package/wouter

Wrap everything as you normally would using react-router-dom but use wouter instead. Note that top level Router component is fully optional.

App.js :

import Nav from './Nav'
import { Router, Switch, Route } from 'wouter';

make App.js a class component and structure like so:

<Nav />
<Router/>
<Switch />
 <Route exact path="/somelink" component={Somecomponent}/>
<Switch />
<Router/>

export default App;

Nav.js component:

import { Link } from 'wouter'
const Nav = () => {
    return (
        <nav className="navigation">
            <ul>
                <li>
                    <Link to="/somecomponent">...</Link>
                </li>
            </ul>
        </nav>
    )
}

export default Nav;
Related