react-router and can't seem to access child dynamic params from a Switch in a parent component

Viewed 30

I've been looking, and seems there isn't a way to do this via react-router, but perhaps I missed something.

NOTE: I am version react-router v5

I have a layout.. ala..

header
 sub-header
   CHILD_ROUTES
footer

problem arises when the url changes and I want to "hide" the header IF a certain child route with a particular param is given.

In general, I have this:

<Route>
  <Header />
  <SubHeader />
  <ChildRoutes />
  <Footer />
</Route>

my child routes:

<Switch>
  <Route path="/product/categories" component={CatComponent} />
  <Route path="/product/:productId?" component={SomeComponent} />
  <Redirect from="*" to="/login" />
</Switch>

How IN the outer scope, where the top level Route is, can I get at "productId", IF that productId is a certain value, I want to remove the header....

I tried useParams, withRouter, useLocation etc.. there is NO "productId" params, UNLESS I do something like (but this is useless for me way down here )

   <Route path="/product/:productId?" component={(props) => {
      console.log(props) // <----- there IS a param value with "productId". 
      return <SomeComponent />
    }} />

I was hoping to do something like:

const returnRoutes = () => {
    const { productId = null } = useParams();

    return (
       <Route>
         {productId != 4 && <Header /> }
         <SubHeader />
        <ChildRoutes />
        <Footer />
      </Route>
    )

}

Of course, I am trying NOT to pass actions around to then set some upper state with this value. I was hoping react-router could handle this behind the scenes. I was hoping not to do something like:

const match = useMatch(location.pathname, {
    path: "/product/:productId",
    exact: true,
    strict: true
}

or

location.pathname.split('/').pop() etc....

I ended up just going with "location.pathname.split...." to get the productId.

0 Answers
Related