reactjshigher-order-components

Higher Order Components - React.JS


Trying to pass initial value 10 to the Higher Order Components.

import HOC from './HighOrderComponent'

class ClickHandler extends Component{
  state= {val : 10}

  increment = () => {
    this.props.increment(this.state.val)
  }

  render(){
    return  <button onMouseOver={this.increment}>Mouse Over {this.props.value}</button>
  }
}
export default HOC(ClickHandler)

Here, I do not know how to use the value to update the state of

const HOC = (OriginalComponent) => {

  class HigherOrderComponent extends Component{

    state = { count : 0 }

    increment = (value) => {
      this.setState(prev => ( {count : prev.count + 1 }))
    }

    render(){
      return <OriginalComponent  value={this.state.count} increment={this.increment}/>
    }}

  return HigherOrderComponent
}
export default HOC

Expected Result: On load, Mover Over 10, once hovered, it will increment to 11, 12, 13.....

thanks.


Solution

  • The issue with your components is that HOC component's state overrode your 10 state defined in your ClickHandler.

    If you changed state = { count : 0 } to state = { count : 10 } you will get the expected initial value of 10.

    But seeing the code, what is the purpose of having state value maintained in both components? And the state value of ClickHandler is not even used by the HOC.

    Guessing you want to maintain the state within HOC and simply wanted to pass in an initial value for it.

    Would suggest the following changes:

    class ClickHandler extends Component{
      // no need to maintain state again in `ClickHandler`
      // simply use the increment props for onMouseOver
      render(){
        return  <button onMouseOver={this.props.increment}>Mouse Over {this.props.value}</button>
      }
    }
    
    // add extra param for HOC to pass in initialValue of 10
    export default HOC(ClickHandler, 10);
    
    
    const HOC = (OriginalComponent, initialValue) => {
    
      class HigherOrderComponent extends Component{
    
        state = { count : initialValue }
    
        // no need to get the state value from `ClickHandler`
        increment = () => {
          this.setState(prev => ( {count : prev.count + 1 }))
        }
    
        render(){
          return <OriginalComponent  value={this.state.count} increment={this.increment}/>
        }}
    
      return HigherOrderComponent
    }