DEV Community

John Kevin Baluyot
John Kevin Baluyot

Posted on

4 3

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay