2

I want to make it so if the user enters an invalid path in the URL it automatically redirects them to the homepage.

Something like this:

<BrowserRouter>
    <Routes>
        <Route exact path="/" element={<Home />}/>
        <Route exact path="/page" element={<page />}/>
        <Route path="*" /*Go to path - "/" */ />
    </Routes>
</BrowserRouter>
Josh Ackland
  • 603
  • 4
  • 19

1 Answers1

6

Render a redirect as the routed component, in this case the Navigate component with the replace prop specified.

<Route path="*" element={<Navigate to="/" replace />} />
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • It does work without replace with react-router-dom 6+. Did not throw any error. – Anil_M Nov 22 '22 at 23:35
  • @Anil_M Sure, you can omit the `replace` prop and issue a PUSH navigation by default. Note that this is a "forward" navigation and a new entry will be PUSH-ed onto the history stack, as opposed to redirecting by REPLACE-ing the current entry in the history stack. – Drew Reese Nov 22 '22 at 23:39