Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 921
Ali Seyfollahi Avatar asked Oct 05 '19 13:10

Ali Seyfollahi


2 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

like image 174
Cullen Bond Avatar answered Oct 04 '22 18:10

Cullen Bond


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

like image 24
roNn23 Avatar answered Oct 04 '22 16:10

roNn23