Updating HTML5 Source URL with React

I want to update the source tag in an HTML5 video element so that when I click the button, all playback switches to a new video.

I have a Clip component that returns an HTML5 video element, with the original URL provided through the details.

function Clip(props) { return ( <video width="320" height="240" controls autoPlay> <source src={props.url} /> </video> ) } 

I also have a Movie component that contains several URLs, each of which corresponds to a section of the movie. It also contains the position attribute, which acts as an iterator, remembering which section is currently playing.

 class Movie extends Component { constructor() { super(); this.state = { sections: [ 'https://my-bucket.s3.amazonaws.com/vid1.mp4', 'https://my-bucket.s3.amazonaws.com/vid2.mp4' ], position: 0 }; } render() { const sections = this.state.sections const position = this.state.position return ( <div> {position} <Clip url={sections[position]} /> <button onClick={() => this.updatePosition()}>Next</button> </div> ) } updatePosition() { const position = this.state.position + 1; this.setState({ position: position }); } } 

The Movie component displays the clip component and the Next button. When I click Next, I want to update the position attribute and redisplay the HTML5 video element using the following URL from the sections.

At the moment, when I click Next, the HTML5 video source tag is updated, but the item continues to play the video from the previous URL. Can someone help me figure out how to reset a video element?

Update: I created a JSFiddle, which you can see here .

Update 2: Update the src attribute on the video element!

+6
source share
2 answers

Changing src <source /> for some reason does not switch the video. This is not a problem, I do not think so. Probably how <source /> works. You may need to call .load() on the element again. But it’s just easier to install it directly on the element itself.

See comment to top answer: Can I use javascript to dynamically change the video source?

You can install src directly on the element:

 function Clip(props) { return ( <video width="320" height="240" src={props.url} controls autoPlay> </video> ) } 
+9
source

Short tag: Add key prop to <Clip> or <video> , for example:

 <Clip url={sections[position]} key={sections[position]} /> 

Long tag: The video will not change, because essentially you are only modifying the <source> element, and React understands that the <video> must remain unchanged, so it does not update its DOM and does not fire a new load event for this source.

To update not only <source> , but also <video> , add key prop to it so that React understands that the whole new element.

For a more complete explanation, check out this article on keys in React docs :)

+7
source

Source: https://habr.com/ru/post/1013471/


All Articles