Search code examples
reactjsreach-router

Split up routes in same router with reach-router


Say I have a lot of routes and I would like to split them up in groups. How would I accomplish this in React with Reach Router?

Example of what I'm basically trying to accomplish:

const Router = () => {
    return (
        <Router>
            <AnonymousRoutes />
            <SecureRoutes />
        </Router>
    );
};

const AnonymousRoutes = () => {
    return (
        <>
            <Page1 path="1" />
            <Page2 path="2" />
        </>
    );
};

const SecureRoutes = () => {
    return (
        <>
            <Page3 path="3" />
            <Page4 path="4" />
        </>
    );
};

Solution

  • Edit: So, I based my answer off of a misreading of your problem statement. I thought I read react-router, not reach router. I apologize.

    So using a fragment is exactly what you probably SHOULD be doing. However, React Reach doesn't currently support fragments. Silver lining, it looks like it will soon!

    https://github.com/reach/router/pull/289

    If I'm understanding your question correctly, I think what you're looking for is Switch from react-router.

    The switch component allows a developer to segment out their routes and render specific content on the path.

    It might look something like this:

    import { Switch, Route } from 'react-router'
    
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/:user" component={User}/>
      <Route component={NoMatch}/>
    </Switch>