Reputation: 12874
I have written two versions of HOC implementation by mistake but it doesn't throw me any mistakes and working as expected, so I'm hoping someone would be able to explain me the differences. requireAuth
is the higher-order-component
First I have a component as below
import requireAuth from 'somepath';
class App extends Component {
...
}
export default connect(null, actions)(requireAuth(App));
Then below is my requireAuth
import React, { Component } from 'react';
import { connect } from 'react-redux';
export default (ChildComponent) => {
class ComposedComponent extends Component {
...
render() {
return <ChildComponent {...this.props}/>;
}
}
function mapStatetoProps(state) {
return { someProp: state.someState };
}
return connect(mapStateToProps)(ComposedComponent);
};
And below is my another version by mistake, but no error and I am looking for some explanation if there is any differences:
import requireAuth from 'somepath';
class App extends Component {
...
}
export default requireAuth(connect(null, actions)(App));//<<=== use requireAuth to surround the whole connect statement instead
And below is the requireAuth
:
import React, { Component } from 'react';
import { connect } from 'react-redux';
export default (ChildComponent) => {
class ComposedComponent extends Component {
...
render() {
return <ChildComponent />; //<<<======without {...this.props}
}
}
function mapStatetoProps(state) {
return { someProp: state.someState };
}
return connect(mapStateToProps)(ComposedComponent);
};
Upvotes: 0
Views: 110
Reputation: 4636
The very first thing one needs to keep in mind using HOC is that, any react component that is wrapped within a HOC , will still yield a react component.
In the first case:
connect(null, actions)(requireAuth(App));
will provide redux props to requireAuth
. Which is passing its props to App
component. So the App component is still getting all the props from redux. So it works as far as I know.
For The second case:
requireAuth(connect(null, actions)(App))
you are passing connect(null,actions)(App)
to the requireAuth
component, as a children component. And only rendering the children component return <ChildComponent />
. Since the App
component is still wrapped by connect
. The App
component will still have all the redux props needed for its execution. So rendering ChildComponent
without props will still work.
And the props obtained from return { someProp: state.someState };
is still usable to requireAuth
, because requireAuth
is wrapped within another connect which will provide requireAuth
the required props from the react state.
So both of the cases look alright theoretically. HOC are there to make our lives better instead of confusing. The first case you present is actually the right way to do things with HOC imo;
Upvotes: 1