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?
This is technically an approach that can be used. But HOCs typically deal with data flow addition/interception, as opposed to UI. IMO, they should be used sparingly. This really feels like overengineering, when you can just have PlayerTimeComtrol
accept a children
prop and wrap it around PlayerComponent
<PlayerTimeComtrol
label={this.props.label}
onChangeHandler={this.updatePlayerDelay}
>
// with whatever component you want here
</PlayerTimeControl>