Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do non-existent routes redirect to homepage in react router dom?

I would like all routes other than those registered below to direct me to the main page.

example:

testexample.com/contact

-> Returns me to the contact page

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

testexample.com/sdlskdsd

-> Route does not exist, return to main page


import { 
  BrowserRouter,
  Routes,
  Route
} from 'react-router-dom'
import Footerpage from './components/footerpage/Footerpage';
import Navegation from './components/navegation/Navegation';
import Homepage from './pages/Homepage';
import Contact from './pages/contact/Contact';
import Bookpage from './pages/bookpage/Bookpage';
import Success from './pages/contact/status/Success';
import Error from './pages/contact/status/Error';

function App() {
  return (
    <BrowserRouter>
      <Navegation />
        <Routes>
          <Route path='/' exact element={<Homepage />} />
          <Route path='/contact' exact element={<Contact />} />
          <Route path='/contactsuccess' exact element={<Success />} />
          <Route path='/contacterr' exact element={<Error />} />
          <Route path='/bookpage' exact element={<Bookpage />} />
        </Routes>
      <Footerpage />
    </BrowserRouter>  
  );
}

export default App;

>Solution :

Redirect unknown/unhandled routes to the "/" path with the Navigate component.

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

Also, in RRDv6 all routes are now always exactly matched, there is no longer any exact prop, so these should all be removed.

Full routes example:

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

...

<Routes>
  <Route path='/' element={<Homepage />} />
  <Route path='/contact' element={<Contact />} />
  <Route path='/contactsuccess' element={<Success />} />
  <Route path='/contacterr' element={<Error />} />
  <Route path='/bookpage' element={<Bookpage />} />
  <Route path="*" element={<Navigate to="/" replace />} /> // <-- redirect
</Routes>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading