Chuck
Chuck

Reputation: 375

Reach Router not showing correct component for matched url

With the following I can navigate to /shop/, /shop/dept1/, /shop/dept2/, and see the component I expect to see.

When I try navigating to /shop/dept1/?option=..., I still only see the DeptOne component, not the PLP component. I'm almost positive I've done something similar to this in the past, but can't seem to replicate it this time.

<Router basepath='/shop'>
    <Shop path='/' />
    <DeptOne path='/dept1/' />
    <DeptTwo path='/dept2/' />
    <PLP path='/dept1/*' />
    <PLP path='/dept2/*' />
</Router>

Upvotes: 0

Views: 191

Answers (1)

Bram Dekker
Bram Dekker

Reputation: 649

URL query parameters (the key-value pairs after the ?) are not part of the path. So for /shop/dept1/?option=... the path is still /shop/dept1/.

This means that the component for path /shop/dept1/ must handle the query parameters. The query parameters can be accessed in the component via the location object, which is a prop for Router (https://reactrouter.com/web/api/location).

You could for example make a wrapper component:

const WrapperComponent = ({ match, location }) => {
  return (
    <>
      <DeptOne />
      {location.search == ""
        ? null
        : <PLP queryParams={location.search}>
      }   
    </>
  );
}

The queryParams prop is a string that starts with the ?. So if the path is /shop/dept1/?option=... queryParams will be ?option=....

More info here.

Upvotes: 1

Related Questions