Search code examples
javascriptreactjsurl-routingreach-router

Multiple path names for a same component in Reach Router


I am using the same component for three different routes:

<Router>
    <Home path="/" />
    <Home path="/home" />
</Router>

Is there anyway to combine it, to be like:

<Router>
    <Home path=["/home", "/"] />
</Router>

Solution

  • For Reach Router: (https://reach.tech/router/example/)

    With the exact sample shown, the only way I can see how to do this(on a single line) is with a wildcard.

    To find a way to reproduce this without side effects, we would need to see the entire nav menu.

      <Router>
        <Home path="/*" />
        <Chicken path="chicken">
      </Router>
    
    ...
    
    const Home = props => {
      let urlPath = props["*"]
      // URL: "/home"
      // urlPath === "home"
      // URL/: "/"
      // urlPath ===""
    }
    

    You could continue with other paths below Home and the router would allow them to process.

    Check out the the example using a wildcard and reach router on codesandbox, I wrote!

    Note: This is a catch-all, but without parsing a parameter is the only single line solution I saw.

    Some DrawBacks include Home rendering instead of '404', etc.

    //This could be resolved with an if statement in your render

    //It will not produce the intended URL either for /home, and I have not looked into that since it is not part of the question.. but if it matched props[*] I'm sure you could redirect or something.

    You can read more about the Route Component for Reach Router. https://reach.tech/router/api/RouteComponent