React Router V4 - Warning: You tried to redirect to the same route you're currently on: "/home/dashboard"
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>
)
I resolved the issue. Here's a solution.
route.js<Provider store={store}>
<BrowserRouter>
<div>
<Route path="/" component={ App }/>
</div>
</BrowserRouter>
</Provider>
At App.js add a check match.url === window.location.pathname
which is always true for initial rendering so '/'
redirects to '/home/dashboard'
. Adding this condition resolves the redirect warning.
class AppComp extends Component {
render() {
const {match} = this.props;
let
shouldRedirect = match.url === window.location.pathname,
redirectTo = <Redirect to="/home/dashboard" />;
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} />}/>
{shouldRedirect && redirectTo}
</div>
</div>
</div>
);
}
}
But you will have a limitation now, if user enters some unknown path then it won't redirect to '/home/dashboard'
i.e to our default route.
To overcome that limitation you have to add :
<Switch>
{/*---- your additional routes goes here -----*/}
<Redirect to="/home/dashboard" />
</Switch>
Add the above code to the components from where you handle rest of the routing. For example for me I have added to Sidenav component.
Even I faced similar issue. It was resolved to me when I added exact in Route.Switch also must be added.
<Switch>
<Route exact path='/' component={ App }/>
</Switch>