React redirecting to 404 Route from id-based Route

Viewed 680

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>
  );
};
1 Answers

Just check whether you are able to get the route params i.e id, in the component or not.If not try to use the path without array and separate it out.

const Main = () => (
  <Switch>
    <Route exact path="/">
      <Redirect to="/home" />
    </Route>
    <Route exact path="/home" component={Home} />
    <Route exact path="/products/:id" component={ProductComponent} />
    <Route exact path="/products" component={CardList} />
    <Route exact path="/about" component={About} />
    <Route exact path="/contact" component={Contacts} />
    <Route component={NotFoundPage} />
  </Switch>
);

For handling the wrong product ids you can check in the components whether there is id param is available or not, else redirect wherever you want.

Related