Call custom method on component when props update

- 1 answer

Ad

I have a YouTubeiFrame react component that renders an empty div and then drops the YouTube iframe player in to that div using componentDidMount. All works fine. I have a cueVideo method defined on the component which uses the players API to cue new videos:

cueVideo(videoId) {
  this.player.cueVideoById(videoId)
}

In different places in my app you can click a button or some another action to indicate that you want to play a new video. When you perform this action the 'currentVideo' state is updated via redux and as a result the YouTubeiFrame component receives the new video id as an updated prop.

My question is how to call the cueVideo method above in reaction to the updated prop. I've considered using shouldComponentUpdate to compare this.props.currentVideo with the next props but concious this method is really supposed to return true/false so the render function can be called. All I want to do is call cueVideo when the currentVideo prop changes - I don't really need to re-render.

What's the best way to do this?

Ad

Answer

Ad

All I want to do is call cueVideo when the currentVideo prop changes - I don't really need to re-render.

When new props are received, React will automatically call render() to update your component. Once all the updates have been flushed to the DOM, React will also call componentDidUpdate() on your component to give you an opportunity to respond to the changes. As the documentation says:

Use this as an opportunity to operate on the DOM when the component has been updated.

I would suggest this is the perfect place to call your code as needed.

Ad
source: stackoverflow.com
Ad