Reputation:
I've recently countered a problem while using react-router-dom. when i used my code like this:
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Route path="/protected" component={PROTECTED} />
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
NoMatch route component worked fine, but when i tried to use some Auth component like this it didn't work:
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Auth>
<Route path="/protected" component={PROTECTED} />
</Auth>
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
so I've read some docs and issues, and eventually reached to conclusion that i need to use only react-router-dom components.No external components or custom components.So my question here is there a work around this problem.Or I've to think of another approach for authentication routes.And if there is no work around, can someone suggest the best way to do this way of authentication inside <BrowserRouter/>
component ?
Upvotes: 1
Views: 412
Reputation: 112917
React Router will only render a single component inside a Switch
. If the path doesn't match /home
, it will check the second component which is Auth
and always render that.
You could instead use the render
prop of the Route
component so that the second component won't match any route except the /protected
route.
<BrowserRouter>
<div>
<Switch>
<Route path="/home" component={HOME} exact />
<Route
path="/protected"
render={() => (
<Auth><PROTECTED /></Auth>
)}
/>
<Route component={NoMatch} />
</Switch>
</div>
</BrowserRouter>
Upvotes: 1