How to write Not found page for React Router v6 for the routes not present?

Viewed 30
<Routes>
  <Route path="/404" element={<NotFound />} />
  <Route path="/" element={<Home />} />
  <Route path=":category" element={<Products />} />
  <Route path='*' element={<NotFound />} />
</Routes>

This is the code that I tried, it is rendering path="/404" but not path="*". Can anyone help me with this one? I looked for answers but I am unable to solve this.

1 Answers

I don't see any issue with the routing code, per se, but I suspect in this case the <Route path=":category" element={<Products />}/> is matching some of these extraneous routes and being rendered. For example, any URL with a single path segment, i.e. "/foo" and "/bar", will be matched as categories. If that's the case then you'll need to validate the category route param and conditionally redirect to the "/404" route. Any route that isn't an exact match should still be matched by the "*" route.

Example:

const navigate = useNavigate();
const { category } = useParams();

useEffect(() => {
  if (/* condition check for category */) {
    navigate("/404", { replace: true });
  }
}, [category]);
Related