Published on

How to Redirect Unauthenticated user in React

Authors

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);
}