You’re going to want to use the Redirect
component. There’s a few different approaches to this problem. Here’s one I like, have a PrivateRoute component that takes in an authed
prop and then renders based on that props.
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
Now your Route
s can look something like this
<Route path="https://stackoverflow.com/" exact component={Home} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<PrivateRoute authed={this.state.authed} path="/dashboard" component={Dashboard} />
If you’re still confused, I wrote this post that may help –
Protected routes and authentication with React Router v4