Hey guys. Here's what I'm trying to do in one of my components
```
...
componentDidUpdate(prev) {
if (prev.isConnected && !this.props.isConnected) {
this.props.history.push('/home');
}
}
...
````
I can't figure out why this isn't navigating to the home directory. I'm pretty new to react router redux. Any insights you have would be really helpful. Thanks
Try this it worked for me
Change routes order from
<App>
<Switch>
<Route path="/" component={LoginPage} />
<Route path="/dashboard" component={DashboardPage} />
</Switch>
</App>
to
<App>
<Switch>
<Route path="/dashboard" component={DashboardPage} />
<Route path="/" component={LoginPage} />
</Switch>
</App>
Thanks @oussamajabnouni, that worked!!
Does anyone have any idea why that worked?
Only a single route in a <Switch> will be rendered. That being said, order matters. React Router uses path-to-regexp to determine a path as a match or not. It's often recommended to put your paths in decreasing specificity because of the scenario you've encountered.
For example, /home will match path="/". Furthermore, /users/add would match both path="/users" and path="/users/add", in which case you'd order path="/users/add" before path="/users".
For your instance, you'd either want to change order as demonstrated by @oussamajabnouni or you can use the exact prop provided by React Router, which is commonly used on the root path.
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/other" component={Other} />
</Switch>
</App>
Now, only / will match path="/" regardless of order.
Route docs and Route Tester are a couple of helpful resources for further exploration.
Most helpful comment
Only a single route in a
<Switch>will be rendered. That being said, order matters. React Router usespath-to-regexpto determine a path as a match or not. It's often recommended to put your paths in decreasing specificity because of the scenario you've encountered.For example,
/homewill matchpath="/". Furthermore,/users/addwould match bothpath="/users"andpath="/users/add", in which case you'd orderpath="/users/add"beforepath="/users".For your instance, you'd either want to change order as demonstrated by @oussamajabnouni or you can use the
exactprop provided by React Router, which is commonly used on the root path.Now, only
/will matchpath="/"regardless of order.Route docs and Route Tester are a couple of helpful resources for further exploration.