I want to update the source tag in a HTML5 video element so that when I click a button, whatever\'s playing switches to a new video.
I have a Clip component that ret
Short awnser: Add a key
prop to <Clip>
or <video>
, e.g.:
function Clip({ url }) {
return (
<video key={url}>
<source src={url} />
</video>
);
}
Long awnser: The video won't change because in essence you're only modifying the <source>
element and React understands that <video>
should remain unchanged, so it does not update it on the DOM and doesn't trigger a new load
event for that source.
To make sure not only <source>
gets updated but also <video>
, add a key
prop to it so React understands that's a whole new element.
For a more complete explanation, check out this article about keys on React docs :)
Changing the src of <source />
doesn't seem to switch the video for some reason. This isn't a react issue I don't think. Probably just how <source />
works. Maybe you have to call .load()
on the element again. But it's just easier to set it directly on the element itself.
See the comment to the top answer: Can I use javascript to dynamically change a video's source?
You can set src
directly on element instead:
function Clip(props) {
return (
<video width="320" height="240" src={props.url} controls autoPlay>
</video>
)
}