Home  >  Article  >  Web Front-end  >  How to Manage Authentication in React Router 4?

How to Manage Authentication in React Router 4?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 23:08:29305browse

How to Manage Authentication in React Router 4?

Managing Authentication in React Router 4

In React Router version 4, the implementation of authenticated routes requires a different approach compared to previous versions.

Original Approach

Previously, you could use multiple Route components with children, but this is now discouraged.

<Route exact path="/&quot; component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>

Correct Implementation

To implement authenticated routes, one option is to use a custom component that extends Route and checks for authentication before rendering the component.

import React, {PropTypes} from "react";
import {Route} from "react-router-dom";

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}

Alternative Approach

Another approach is to use the Redirect component, which allows you to redirect users based on an authed property.

function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

You can then use the PrivateRoute component in your routes:

<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />

The above is the detailed content of How to Manage Authentication in React Router 4?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn