React Js, refactor my redirect methods

I have multiple components where i check if user is auth to redirect on login page

componentWillReceiveProps({auth}) {
    if (auth) {
      this.props.history.push('/login') 
    }
  }

I have copy this code ten times, there is a best way to do that ? I want to refactor do you have solution ?

Thanks

1 answer

  • answered 2018-01-11 20:54 dashton

    The recommendation for cross-cutting concerns such as this is to use higher order components.

    HOCs allow you to wrap your existing component so you can intercept props and apply higher-order logic such as authentication or logging or whatever and then pass the props down to the wrapped component when the HOC has done its work.

    A rough example could be:

    function withAuth(WrappedComponent) {
        return class extends React.Component {
    
         componentWillReceiveProps({ auth }) {
            if (auth) {
               // redirect
            }
          }
          render() {
            return <WrappedComponent {...this.props} />;
          }
        };
      }
    

    Usage would be:

    const Hoc = withAuth(MyExistingComponent);
    ...
    render() {
        return <Hoc {...props} />
    }
    

    A base class is an alternative but would quickly lose focus and become a dump for general shared logic. I think HOC is cleaner.