Home > Blockchain >  How to render page 404 on dynamic routes : React
How to render page 404 on dynamic routes : React

Time:07-18

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

CodePudding user response:

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
  • Related