0

Below push will redirect the URL to http://localhost:3000/search?category=furniture&city=San+Jose%2C+CA%2C+USA when I choose the furniture for the category and "San Jose, CA, USA" for the city.

    this.props.history.push({
      pathname: '/search',
      search: "?" + new URLSearchParams({category: this.category, city: this.userCity}).toString()
    });

In App.jsx, I defined a route like below:

<Route path="/search/:category?/:city?" component={props => <EventSearchPage {...props} />}/>

In the EventSearchPage component, when I tried to access this.props.match.params, I see both category and city are undefined.

Can someone kindly let me know where went wrong? Thanks!

damingzi
  • 676
  • 10
  • 28

2 Answers2

1

When adding parameters to routes with react router, you can do it this way so that they are given to the component.

this.props.history.push({
  pathname: `/search/${this.category}/${this.userCity}`,
});

The route component would look something like this to receive these parameters.

<Route path="/search/:category?/:city?" component={props => <EventSearchPage {...props} />}/>

Documentation for react router can be found here

ppak10
  • 2,103
  • 3
  • 13
  • 24
  • It's not working. When taking ? off the Route path, it just couldn't find the page and return 404 error. – damingzi Aug 17 '19 at 23:46
  • Oh my mistake, I didn't realize that including `?` meant it would take the inputs to the route as an optional parameters. This [answer](https://stackoverflow.com/questions/37696391/multiple-params-with-react-router) explains more but I think you can keep the `?` if you have a link directed to `http://localhost:3000/search` – ppak10 Aug 17 '19 at 23:50
0

Found out queryString can do the trick to get the URL params like doing below:

queryString.parse(this.props.location.search)

npm package link is here: https://www.npmjs.com/package/query-string

damingzi
  • 676
  • 10
  • 28