Given a standard compose function and a 'div' Component, how would you write the two HOCs such that:
- The 'div' element starts as a 20px green box, then on click, becomes a 50px blue box.
- The concerns of - a: merging state with props, and b: triggering a state change, are handled by separate HOCs.
- the updater HOC maps state to props, and sets a default state
- the dispatcher HOC accepts a function to get the new state on click
The example below works to get a green box, and correctly fires the handler. The update only happens in the state of the Dispatcher HOC's state. The updater HOC's state remains unchanged, as do its props.
I'm really curious to understand what's happening. Flipping the two HOCs' order in compose causes the handler not to be set. Since they both merge in {...this.props}, that doesn't make sense to me. Guessing there's something I don't understand about how multiple HOCs merge props and state.
const HOCDispatcher = myFunc => BaseComponent => {
return class Dispatcher extends React.Component {
constructor(props,context){
super(props,context);
this.handlerFn = (event)=>{this.setState(myFunc)}
}
render(){
return createElement(BaseComponent,{...this.props,onClick:this.handlerFn});
}
}
}
const HOCUpdater = defaultState => BaseComponent => {
return class Updater extends React.Component {
constructor(props,context){
super(props,context);
this.state = Object.assign({},defaultState,this.state);
}
render(){
return createElement(BaseComponent,{...this.props,...this.state});
}
}
}
const MyComponent = compose(
HOCDispatcher(()=>({
style:{width:'50px',height:'50px',background:'blue'}
})),
HOCUpdater({
style:{width:'20px',height:'20px',background:'green'}
}),
)('div');
If you try to simplify or compile your code in a way to a less complicated structure you can understand it better:
The initial version of MyComponent
Where
HOCUpdateralso renders as:Thus rendering the green box.
After triggering the click
If you pay attention to the render, it's still the same because
this.propshas not changed and it is still empty. Thus no change to the style of the box whereas the state of theDispatcheris changed!Did you see where you went wrong? Well, just change
this.propstothis.statein theDispatcherand you'll see the magic happen.But wait, there's more!
What happens if you have a line of code like this?
Well, it still renders the first one (the blue box) but to avoid this try changing the render method of
HOCUpdaterto this:and also add a
componentWillReceivePropsmethod, so yourHOCUpdaterwill look like this: