Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect wrong behavior in react-router-dom

I'm using react-router-dom in my reactjs application, and I have this block at the end of my routes to redirect all the wrong paths to this one:

 <Router>
  <React.Suspense fallback={loading}>
    <Switch>
//...all my routes...
//at the end of my routes I have this
     <Route path="*">
      <Redirect to="/dashboard" />
     </Route>
    </Switch>
  </React.Suspense>
 </Router>

If I add a random route like /nonexistentroute it redirects me to /dashboard but, If I'm in a specific route like /home and I click on the refresh button of chrome, I'm being redirected to the /dashboard when it should keep me in the same route. How can I fix it?

like image 485
YaraR Avatar asked Oct 17 '25 11:10

YaraR


2 Answers

You can use Navigate from latest version of react-router-dom to redirect to a different page.

import React, { Component } from 'react';
import Test_1 from './components/Test_1';
import Test_2 from './components/Test_2';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Navigate } from 'react-router-dom';
class App extends Component {
  render() {
    return (
      <Router>
        <Routes>
          <Route path='/' element={<Test_1 />} />
          <Route path='/home' element={<Test_2 />} />
          <Route path='*' element={<Navigate to='/' />} />
        </Routes>
      </Router>
    );
  }
}

export default App;
like image 194
Daniyal Malik Avatar answered Oct 20 '25 03:10

Daniyal Malik


Try writing like this if you are using react-router-dom version 6

<Routes>
      <Route path="/" element={<Homepage />} />
      <Route path="*" element={<ErrorPage />} />
</Routes>
like image 40
Mriganka Saha Avatar answered Oct 20 '25 02:10

Mriganka Saha