jeudi 19 mars 2020

Is this a valid React HoC use case?

I'm introducing myself to React's HoC pattern.

I have a video player component that sometimes needs to have a select to change a parameter in the video src url.

To simplify things, this a reduced version of my HoC:

function withTimeControl(PlayerComponent) {
  return class extends Component {
    state = {
      src: ''
    }

    updatePlayerDelay = (event) => {
      this.setState({
        src: event.target.value
      })
    }

    render() {
      return(
        <div>
          <PlayerComponent 
            title={this.props.title}
            src={this.state.src}
          />

          <PlayerTimeComtrol
            label={this.props.label}
            onChangeHandler={this.updatePlayerDelay}
          />
        </div>
      );
    }
  };
}

And to use it, I would do:

const PlayerWithTimeControl = withTimeControl(Player)

// ...

<PlayerWithTimeControl title='Player title' label='Time control label' />

Where PlayerComponent is the component being wrapped. The HoC basically ads a component, PlayerTimeComtrol to change the src of the video player.

Is this valid use case? Are there other more accurate solutions to this? Maybe just use a component wrapper and not a HoC?

Aucun commentaire:

Enregistrer un commentaire