Multiple path names for a same component in Reach Router

Viewed 3286

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>
4 Answers

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

Depending on the situation you're dealing with, <Redirect /> could also make the work.

<Router>
  <Redirect from="/" path="/home" noThrow />
  <Home path="/home" />
</Router>

You can use a single component for mutiple paths, by using a array of routes.

code example :

import sampleComponent from './sampleComponent'; // single component for mutiple routes

 <Router>
  <Switch>
   {["/pathname_1", "/pathname_2", "/pathname_3", "/pathname_4", "/pathname_5", "/pathname_6"].map(pathname =>  (<Route exact path={pathname} component={sampleComponent} />) )}
   <Switch>
<Router>
Related