I have such Routes. When I type wrong top tree path, like /homedsf - it redirects to NotFoundPage component like it should. But when I do it in products like /products/dsf, it just does not open needed product and stays on products page. How should I handle these wrong id's?
const Main = () => (
<Switch>
<Route exact path="/">
<Redirect to="/home" />
</Route>
<Route exact path="/home" component={Home} />
<Route exact path={['/products/:id', '/products']} component={CardList} />
<Route exact path="/about" component={About} />
<Route exact path="/contact" component={Contacts} />
<Route component={NotFoundPage} />
</Switch>
);
const Products = () => <CardList />;
const CardList = ({ match, history }) => (
<ul className="card-section">
{сardData.map((card) => (
<Card
key={card.id}
isSelected={match.params.id === card.id}
history={history}
{...card}
/>
))}
</ul>
);
UPD: Thanks to Nitin Dev's answer, I implemented it this way:
const CardList = ({ match, history }) => {
useEffect(() => {
const { id } = match.params;
const exists = сardData.find(el => el.id === id);
if (id && !exists) {
history.push('/404');
}
}, [match]);
return (
<ul className="card-section">
{сardData.map(card => (
<Card
key={card.id}
isSelected={match.params.id === card.id}
history={history}
{...card}
/>
))}
</ul>
);
};