0

I want to create an auth HOC that will redirect the user or show the component.

ie:

const AuthExtender = props => {
    if (!props.logged) return <Redirect to="/login" />;

    return <WrappedComponent />;
}

const authCompWithState = connect(state=>({logged:state.logged}))(AuthExtender);

I know this is not right, but this is the idea I want to have:

const MembersPageForLoggedOnly = memberOnlyPageHOC(MemebersPage);

I tried so many version of a function that returns function, but I can't nail it...

Any ideas?

Thanks!

Tzook Bar Noy
  • 10,111
  • 12
  • 45
  • 75
  • are you using react-router? If that's the case, this [answer](https://stackoverflow.com/a/43171515/8371135) helped me to achieve this functionality – Rodrigo Ferreira Jun 19 '18 at 14:49

2 Answers2

0

The usual usage of HOC I have seen is it returns a class:

const authExtender = WrappedComponent => {
   return class extends Component {
     render() {
       if(!this.props.loggedIn) {
         return <Redirect to={'/login'} />;
       }

       return <WrappedComponent {...this.props} />;
     }
   }
};

And then:

export default authExtender(SomeComponent);
Anthony
  • 5,911
  • 2
  • 13
  • 30
0

Using this code, you can create a HOC with just one function and connect it to the store.

const membersOnly = WrappedComponent => {
  
  // render redirect if not logged, else component
  const comp = ({ logged, ...props }) => {
    return logged ? <Redirect /> : <WrappedComponent {...props} />
  }

  // connect it to store
  return connect(state => ({logged: state.logged}))(comp)
}

// render
const HomePageMembersOnly = membersOnly(HomePage)

you could also compose it separatly.

const membersOnly = WrappedComponent => ({ logged, ...props }) => {
  return logged ? <Redirect /> : <WrappedComponent {...props} />
}

// use it directly
const MembersOnlyHomePage = connect(state => ({logged: state.logged}))(membersOnly(HomePage))

fyi remember to always pass unused props to your WrappedComponent.

Luke
  • 7,250
  • 3
  • 20
  • 33