Home > Software engineering >  Redirect wrong behavior in react-router-dom
Redirect wrong behavior in react-router-dom

Time:01-22

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:

<Route path="*">
    <Redirect to="/dashboard" />
</Route>

But whenever I reload any page on my website, I'm being redirected to the dashboard. It's a wrong behavior. How can I fix it?

CodePudding user response:

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

<Routes>
      <Route path="/" element={<Homepage />} />
      <Route path="*" element={<ErrorPage />} />
</Routes>

CodePudding user response:

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;

CodePudding user response:

From your description it sounds like you are rendering several routes into a router without a Switch component. Routers inclusively match and render routes while the Switch exclusively matches and renders the first Route or Redirect component. In other words, a router will render all matches, redirects included, the Switch renders only the first.

Wrap your routes in a Switch and place the redirect last in the list so if no other route path was previously matched the Redirect will render.

<Switch>
  ... all other routes ...
  <Redirect to="/dashboard" />
</Switch>

This OFC, all assumes you are still using react-router-dom v5 since you made no mention of any Redirect component import errors (Redirect was removed in RRDv6). If this isn't the case and you are actually using RRDv6 then please update your question to include a more complete code example.

  •  Tags:  
  • Related