Yash Gupta
Yash Gupta

Reputation: 165

What is best option to guard your routes in React?

I am using this HOC to guard my routes but I find odd using this HOC in every component because I am already using 1 or 2 HOC's like reduxForm etc

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

export default ChildComponent => {
  class ComposedComponent extends React.Component {

    componentDidMount() {
      this.shouldNavigateAway();
    }

    componentDidUpdate() {
      this.shouldNavigateAway();
    }
    shouldNavigateAway() {
      if (!this.props.auth) {
        this.props.history.push("/");
      }
    }
    render() {
      return <ChildComponent {...this.props} />;
    }
  }
  const mapStateToProps = state => {
    return { auth: state.auth };
  };
  return connect(mapStateToProps)(ComposedComponent);
};


Upvotes: 0

Views: 1640

Answers (2)

atadnmz
atadnmz

Reputation: 311

I do not know how you implement your routes but there is clean solution for this.

render() {
    let routes = (
      <Switch>
        <Route path="/auth" component={asyncAuth} />
        <Route path="/" exact component={BurgerBuilder} />
        <Redirect to="/" />
      </Switch>
    );

    if (this.props.isAuthenticated) {
      routes = (
        <Switch>
          <Route path="/checkout" component={asyncCheckout} />
          <Route path="/orders" component={asyncOrders} />
          <Route path="/logout" component={Logout} />
          <Route path="/auth" component={asyncAuth} />
          <Route path="/" exact component={BurgerBuilder} />
          <Redirect to="/" />
        </Switch>
      );
    }

    return (
      <div>
        <Layout>
          {routes}
        </Layout>
      </div>
    );
  }

And store the auth token in your redux.

const mapStateToProps = state => {
  return {
    isAuthenticated: state.auth.token !== null
  };
};

Upvotes: 0

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15821

The HoC approach is right, but you should apply it to routes, not components.

Take a look at the pattern used in redux-auth-wrapper

Upvotes: 1

Related Questions