Multiple path names for a same component in Reach Router
Asked Answered
D

4

8

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>
Dap answered 5/10, 2019 at 13:36 Comment(3)
Duplicate of: #40542494Bander
That's for React Router, This is for Reach Router @BanderDap
You are right. Sorry. My bad.Bander
N
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

Newton answered 11/10, 2019 at 20:8 Comment(1)
First link is broken.Mcmurray
Q
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

Quadruplet answered 16/9, 2020 at 15:50 Comment(0)
I
0

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

<Router>
  <Redirect from="/" path="/home" noThrow />
  <Home path="/home" />
</Router>
Iceberg answered 28/1, 2022 at 16:38 Comment(0)
D
-4

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>
Digastric answered 10/10, 2019 at 12:46 Comment(1)
That's for React Router, I'm looking for solution in Reach RouterDap

© 2022 - 2024 — McMap. All rights reserved.