Reputation: 4607
I have this piece of code in my index.js
:
const routing = (
<Router>
<div>
<Route path='/'>
<Redirect to="/login" />
</Route>
<Route path="/login" component={Login} />
<Route path="/signin" component={Signin} />
<Route path="/home" component={Home} />
</div>
</Router>
)
So what it should give me is, whenever I start it, it should land on http://localhost:3000/login
or somewhere like it. What it does.
It gives me a login screen, where if I click on Login button it takes me to http://localhost:3000/home
, which is also as I intended.
But whenever I directly try to access http://localhost:3000/home
or http://localhost:3000/signin
, it always takes me to http://localhost:3000/login
.
What is the actual problem here? How this can be resolved ?
Upvotes: 1
Views: 722
Reputation: 1422
You need to add the keyword exact
to your routes to specify specific route paths according to the URL, or it will follow the line of succession. For example, if you visit the URL /
it will load the login component as expected because that is the first route. However, if you visit the URL /home
it will render the login component because it contains the path /
. Adding the exact
keyword means ONLY the URL /
will hit that route. Any other routes, even if they contain /
(which is every route) will not render that component because /
is not the EXACT same route as /anything
.
const routing = (
<Router>
<Switch>
<Route exact path='/'>
<Redirect to="/login" />
</Route>
<Route path="/login" component={Login} />
<Route path="/signin" component={Signin} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)
Upvotes: 1
Reputation: 120
Try use exact
on <Route path='/'>
and <Switch>
instead of <div>
:
import { Switch } from 'react-router-dom';
const routing = (
<Router>
<Switch>
<Route exact path='/'>
<Redirect to="/login" />
</Route>
<Route path="/login" component={Login} />
<Route path="/signin" component={Signin} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)
I think there will be problem with partial matching of path. When you try directly access http://localhost:3000/home
first match in router is /
and it redirects you to login.
When you use exact
in <Route>
it matches absolute path. In example above you will be redirected only when you access http://localhost:3000/
<Switch>
groups and iterate <Router>
children elements and renders first match.
In your case (without <Switch>
) it's rendering all <Routes>
. Therefore is probably triggered redirect.
Upvotes: 1