React Router V4 - Warning: You tried to redirect to the same route you're currently on: "/home/dashboard"

Arjita Mitra picture Arjita Mitra · Nov 24, 2017 · Viewed 25k times · Source

I am getting this error tried different ways of routing still no luck.

I have route config file i.e route.js

const Root = ({ store }) => (
    <Provider store={store}>
        <BrowserRouter>
            <div>
                <Route path='/' component={ App }/>  
            </div>
        </BrowserRouter>
    </Provider>
)

Now at App.js

class AppComp extends Component {
    render() {
        const {match} = this.props;
        let navClass = 'active';

        if(this.props.sideClass === "nav-ssh") {
            navClass = "active-ssh"; 
        }

        return (
            <div>
                <div className="container">
                    <div className="main">
                        <Route render={()=><Header sideNavClass={this.props.sideNavClass} />} />
                        <Route render={()=><SideNav navActiveClass={navClass} currentLocation={this.props.location.pathname} />}/>
                        <Redirect to="/home/dashboard" />s
                    </div>
                </div>
            </div>
        );
    }
}

I want to load app always so put it in the highest level and header and sidenav should also gets loaded always so they are inside app.

For any unknown path and for first time load I redirected to /home/dashboard

I understand it must be coming to / twice so this warning.

How can I configure my router to achieve the same and resolve the warning.

Any help would be greatly appreciated.

Answer

UtkarshPramodGupta picture UtkarshPramodGupta · Nov 5, 2018

Use <Switch>, instead of <div> to wrap the routes.

import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { LoginScreen, LogoutScreen } from './components'

export default () => (
  <div>
    <Router>
      <Switch>
        <Route path='/login' component={LoginScreen}/>
        <Route path='/logout' component={LogoutScreen}/>
        <Route component={AuthenticatedRoutes}/>
      </Switch>
    </Router>
  </div>
)