3
votes

I have following routing configuration:

return (<div>
        <Router>
          <div>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer>
              <Route path='/abc' component={abc} />
            </EnsureLoggedInContainer>
          </div>
        </Router>
      </div>
);

The EnsureLoggedInContainer is:

import React from 'react';
import { connect } from "react-redux";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            // this.props.history.push('/login');
            this.context.router.push('/contact');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return this.props.children;
        }
        else
        {
            return null;
        }
    }


}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(EnsureLoggedInContainer);

But, the history push: this.props.history.push('/login'); isn't working. Here history is not present.

If I am using a configuration like this:

<Route component={EnsureLoggedInContainer}>
              <Route path='/myjs' component={MyjsPage} />
            </Route>

I am getting issue like:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

What's the best way of authentication in reactjs?

1

1 Answers

1
votes

From what I can see of your React Router Design, you seem to be using React router version 4

In that case you can specify the route in the Component Itself, and make use of withRouter to do a dynamic redirect like

return (<div>
        <Router>
          <div>

            <Route path='/login' component={LoginPage}/>
            <EnsureLoggedInContainer/>
          </div>
        </Router>
      </div>
);

and

import React from 'react';
import { connect } from "react-redux";
import {withRouter} from "react-router";

class EnsureLoggedInContainer extends React.Component
{
    componentDidMount() {
        if ( !this.props.isLoggedIn )
        {
            this.props.history.push('/login');

        }
    }

    render() {
        // console.log(this.props);
        if ( this.props.isLoggedIn )
        {
            return <Route path='/abc' component={abc} />
        }
        else
        {
            return null;
        }
    }


}
const mapStateToProps = (state,ownProps) => {
    return{
        isLoggedIn : state.isLoggedIn,
        // currentURL : this.props
    }
}

export default connect(mapStateToProps)(withRouter(EnsureLoggedInContainer));