DEV Community

John Kevin Baluyot
John Kevin Baluyot

Posted on

React v17 - Redirect route if the URL didn't exist

I'm practicing react v17 and react-router-dom v6 a bit lately and I stumbled to a simple problem.

How to redirect a page when the URL doesn't exist in your application?

Kinda like this. Let say you went to localhost:3000/login and that URL doesn't exist in your react application. What I want to happen is to redirect to a certain URL, like localhost:3000/404

What I did to solve this problem was, first is to create MissingRoute.js

import { Navigate } from 'react-router-dom';

function MissingRoute() {
   // pathname can be change based on what url you want to redirect to
   return < Navigate to={{pathname: '/404'}} / >
}

export { MissingRoute }
Enter fullscreen mode Exit fullscreen mode

Then I use it in the routes:

import { MissingRoute } from './path/to/file';

function App() {
  return (
    <BrowserRouter>
     <Routes>
      <Route path="*" element={<MissingRoute/>} /> 
     </Routes>
    </BrowserRouter>
  )
}
Enter fullscreen mode Exit fullscreen mode

This way it would redirect to localhost:3000/404 each time you input an invalid URL.

Top comments (0)