How to Redirect Unauthenticated user in React

May 07, 2017

Here’s a little snippet of how to do it using react-router & react-redux

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';

export default function (ComposedComponent) {
  class Authentication extends Component {
    static contextTypes = {
      router: React.PropTypes.object,
    };

    componentWillMount() {
      if (!this.props.authenticated) {
        // browserHistory.push(`/login/?redirect=${this.props.nextPath}`);
        window.location = '/login';
      }
    }

    render() {
      return <ComposedComponent {...this.props} />;
    }
  }

  function mapStateToProps(state) {
    // You need to have a state for auth. Using which we'll redirect.
    return {
      authenticated: state.auth.authenticated,
    };
  }

  return connect(mapStateToProps)(Authentication);
}

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP