7

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>
Ali Seyfollahi
  • 2,047
  • 1
  • 16
  • 27

4 Answers4

2

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

Cullen Bond
  • 382
  • 1
  • 5
2

I wasn't happy with the wildcard solution from the documentation and @cullen-bond because I had to map many other paths and came up with this solution:

<Router>
  {["/home", "/", "/other", "/a-lot-more"].map(page => <Home path={page} />)}
</Router>

Example: https://codesandbox.io/s/reach-router-starter-v1-forked-6f44c?file=/src/index.js

roNn23
  • 1,207
  • 1
  • 13
  • 28
-2

I think you can do it like you wanted to. Take a look at this: https://reacttraining.com/react-router/core/api/Route/path-string-string

Nikola Ravic
  • 332
  • 3
  • 8
-3

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>
Hemant
  • 125
  • 1
  • 10