How to redirect to home page if url is invalid

Viewed 28

here is my code

<Routes>
    <Route path='/' element={<User/>} />
    <Route path='/:userId/places' exact element={<UserPlaces/>} />
    <Route path='/places/new' element={<NewPage/>}/>
    <Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
</Routes>

I want to redirect to the homepage if anything other than these URLs is entered, but using the redirect method in the latest version is not supported.

3 Answers

Add all matching Route at the end of your Routes:

<Routes>
  ...
  ...
  <Route path='*' element={<Home/>}></Route>
</Routes>

You can easily do that with React Router. If no page is found then you can use * in Path ‍and the element you can use your preferred component Like <Homepage /> or <NotfoundPage />

<Routes>
    <Route path='/' element={<User/>} />
    <Route path='/:userId/places' exact element={<UserPlaces/>} />
    <Route path='/places/new' element={<NewPage/>}/>
    <Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
    <Route path='*' element={<Homepage/>} />
</Routes>

The Navigate component effectively replaced the older Redirect component. Render a "wildcard" route that renders a redirect to your home page route.

Example:

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

is equivalent to RRDv5's <Redirect from="*" to="/" />

Code:

import { Routes, Route, Navigate } from 'react-router-dom';

...

<Routes>
  <Route path='/' element={<User />} />
  <Route path='/:userId/places' element={<UserPlaces />} />
  <Route path='/places/new' element={<NewPage />} />
  <Route path='/places/:placeId' element={<UpdatePlace />} />
  <Route path="*" element={<Navigate to="/" replace />} />
</Routes>
Related