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

How to render page 404 on dynamic routes : React

i’m trying to redirect the user if he types a wrong id in the route below, to the Page404.
I tried to create a new route with path="/location/*" but it doesn’t seem to be working properly.

Thanks in advance for your help.

          <Route path="/location/:id" element={<LocationPage/>} />
          <Route path="*" element={<Page404/>} />
import React, {Fragment, useEffect} from 'react'
import { useParams } from 'react-router-dom';
import locations from "../data/data.json";
import { Carousel, Infos } from "../components/LocationPageComponents"
import { Accordeon } from '../components';

const LocationPage = () => {
  const { id } = useParams();
  const location = locations.find(location => location.id === id)
  
    return (
      <Fragment>
        <Carousel pictures={location.pictures} key={"Carousel"}/>
        <Infos currentLocation={location}/>
        <div className="more-infos">
          <Accordeon content={{title: "Description", reply: location.description }} />
          <Accordeon content={{title: "Équipements", equipments: location.equipments }} />
        </div>
      </Fragment>
    )
}

export default LocationPage

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

>Solution :

Even when you type an id that doesn’t exist to your location path, the fallback path won’t be triggered because the routing is correct. The url is matched and it will show the LocationPage component.

What you can do it is show an empty location component when no location is found.
Or use an effect to route to a different page, but this might not be what you want.

const LocationPage = () => {
  const { id } = useParams();
  const location = locations.find(location => location.id === id);

  if (!location) {
    return <EmptyLocationPage />
  }


  // ...
}

Your fallback route will only be triggered by routes that are not defined in your routes component. Like these for example:

/location/1/fail
/locations
/location
/whatever
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