Home > Net >  React router v5 create a path with two optional params
React router v5 create a path with two optional params

Time:10-19

How to create a path that can handle zero, one, the other or both parameters at once.

For example:

/offers /offers/q-shoes /offers/London /offers/London/q-shoes

I am trying to achieve it this way, unfortunately in this case the path /offers/London is not captured

import React from 'react';
import pathToRegexp from 'path-to-regexp';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import { Home, Browse } from './Pages';

const re = pathToRegexp('/offers/:location?/q-:search?');

const App = () => (
  <Router>
    <Switch>
      <Route path={re}>
        <Browse />
      </Route>
     
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  </Router>
);

export default App;

CodePudding user response:

Create multiple paths that lead to the same component:

<Route path="/offers/q-shoes">
    <RelevantComponentHere />
</Route>
<Route path="/offers/London">
    <RelevantComponentHere />
</Route>
<Route path="/offers/London/q-shoes">
    <RelevantComponentHere />
</Route>
<Route path="/offers/q-shoes/London">
    <RelevantComponentHere />
</Route>

As you can probably tell, this is not ideal. What you could do instead, is to turn the paths into actual URL parameters (e.g. "/offers?q-shoes=true&London=true"). In that case, you only have one path:

<Route path="/offers">
    <RelevantComponentHere />
</Route>

and you can then use the useParams or the useLocation hook to find the relevant parameters and use them.

  • Related