Home > Back-end >  How to redirect to home page if url is invalid
How to redirect to home page if url is invalid

Time:09-11

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.

CodePudding user response:

Add all matching Route at the end of your Routes:

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

CodePudding user response:

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