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>
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.
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>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With