Authenticated Routing in React Router 4
Authenticated routes in React Router 4 require a different approach than in previous versions. React Router 4 no longer supports nested routes with component and children props, which makes it more challenging to implement authenticated routes.
Solution: Using Redirect Component
To implement authenticated routes, you can use the Redirect component. The Redirect component redirects the user to a different path based on a given condition.
Consider the following PrivateRoute component:
<code class="javascript">function PrivateRoute ({component: Component, authed, ...rest}) { return ( <Route {...rest} render={(props) => authed === true ? <Component {...props} /> : <Redirect to={{pathname: '/login', state: {from: props.location}}} />} /> ) }</code>
This component renders the specified component if the user is authenticated (anthed === true); otherwise, it redirects the user to the login page.
Usage:
Now, you can use the PrivateRoute component in your routes like this:
<code class="javascript"><Route path='/' exact component={Home} /> <Route path='/login' component={Login} /> <Route path='/register' component={Register} /> <PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} /></code>
In this example, the PrivateRoute for the dashboard route will redirect unauthenticated users to the login page.
Alternate Solution: Dispatching Actions
Another approach, which may be less desirable, is to dispatch an action in the render method of your AuthenticatedRoute component. This might look like:
<code class="javascript">export default class AuthenticatedRoute extends React.Component { render() { if (!this.props.isLoggedIn) { this.props.redirectToLogin() return null } return <Route {...this.props} /> } }</code>
This approach triggers a redirect to the login page when the user is not logged in, but it may feel less elegant than using the Redirect component.
The above is the detailed content of How to Implement Authenticated Routing in React Router 4?. For more information, please follow other related articles on the PHP Chinese website!