React Router v6 - Create Invalid Path Redirect

Viewed 801

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>
1 Answers

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

<Route path="*" element={<Navigate to="/" replace />} />
Related