react correct url dom router

Viewed 23

I'm creating my first react application, I can't find how to prevent the user from accessing a route that is not part of the application. Knowing that there are routes with authentication and others without authentication. I am using react-router-dom@6 for my routes with mandatory authentication I found.

<BrowserRouter>
  <header className="App-header">
    <Navigation />
  </header>
  <Routes>
    <Route path={"/"} element={<Accueil />} />
    <Route path={"notre-histoire"} element={<OurHistory />} />
    <Route path={"notre-savoir-faire"} element={<OurExpertise />} />
    <Route path={"l-actualite"} element={<News />} />
    <Route path={"les-patisseries/les-exclusifs"} element={<Exclusifs />} />
    <Route path={"les-patisseries/les-classiques"} element={<Classiques />} 
    <Route path={"inscription"} element={<Registration />} />
  </Routes>
  <Footer />
</BrowserRouter>
1 Answers

Using react-router-dom alone you can render a "catch all" path="*" route that will be matched if no other route paths match the current URL path. On this route you can render any "404" content necessary.

Note that this not an HTML server redirect to a 404 page, but client-side routing.

Example:

<BrowserRouter>
  <header className="App-header">
    <Navigation />
  </header>
  <Routes>
    <Route path="/" element={<Accueil />} />
    <Route path="notre-histoire" element={<OurHistory />} />
    <Route path="notre-savoir-faire" element={<OurExpertise />} />
    <Route path="l-actualite" element={<News />} />
    <Route path="les-patisseries/les-exclusifs" element={<Exclusifs />} />
    <Route path="les-patisseries/les-classiques" element={<Classiques />} 
    <Route path="inscription" element={<Registration />} />
    <Route path="*" element={<div>404</div>} /> // <-- "catch all" 404 route
  </Routes>
  <Footer />
</BrowserRouter>
Related