Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Component is not rendering in Nested Routing

I am using "react-scripts": "4.0.2" and all my components are React Hooks. My logic involves nested routing but the end result is not rendered.

Body.js:

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js:

const expandFormHandler = (pid) => {
console.log("PID:" + pid);           //It is printing correcly
props.history.push({ pathname: "/form/" + pid });  //URL is also changing accordingly
}

return (
<div>
  {prodCards.map((card, index) => (
    <ProductCard
      key={index}
      expand={expandFormHandler.bind(this, card.pid)}
    />
  ))}

  <Route path={props.match.url + "/:id"} exact component={Modal} />
//<Route path="/form/:id" exact component={Modal} />   //Tried this too
</div>
  );

Modal.js:

<h1>{props.match.params.id}Hello</h1>

The modal is not rendering even it's useEffect() is not executed.

Now if I place Modals Route in Body.js like following the Modal is rendered but not in the same page below ProductCard

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/form/:id" exact component={Modal} />
    <Route path="/" exact component={ShopCards}></Route>
</Switch>
like image 696
VKT Avatar asked Nov 24 '25 19:11

VKT


1 Answers

Issue

The Route rendering Forms is using an exact match, i.e. when the path is exactly "/form"

<Switch>
  <Route path="/form" exact component={Forms}></Route> // <-- exact match!!
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

When the path is any subroute, i.e. "/form/3" it is no longer an exact match and Form is no longer rendered.

Solution

Remove the exact prop from the root route.

<Switch>
  <Route path="/form" component={Forms}></Route> // <-- general match
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js

return (
  <div>
    {prodCards.map((card, index) => (
      <ProductCard
        key={index}
        expand={expandFormHandler.bind(this, card.pid)}
      />
    ))}

    <Route path="/form/:id" component={Modal} /> // <-- more specific match
  </div>
);
like image 146
Drew Reese Avatar answered Nov 27 '25 09:11

Drew Reese