Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

404 page not found not working react-router v6 (using more than one param)

My shallow understanding is causing a simple issue with rendering the NotFound page…

<Routes>
          <Route path="*" element={<NotFound />}/>
          <Route path="/" element={<Home />} />
          <Route path="/:category/:id" element={<Article />} />
        </Routes>

When the uri contains one "/", it renders the matching component or NotFound component, however, when the uri includes two "/", for example "/asoejdnxx/acnoiw" which doesn’t exist, it doesn’t route to the NotFound page but just renders a blank page with no errors.

I’m assuming the issue is because react is looking for the params in the thirds Route(which has the :category and :id param) regardless of it matching or not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m sure there should be no need to add a condition in the "Article" component, such as if the param doesn’t match to an existing :id, render something else(since thats the purpose of path="*"), but i cant find a way to redirect or render the NotFound component.

>Solution :

You can manually redirect the user to the 404 page:

import { useNavigate } from "react-router-dom";
const YourComponent = () => {
    const navigate = useNavigate();
    if(/*some condition*/){
        navigate("/404");
    }
    return /*...*/
}```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading