54

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 returns an HTML5 video element, with the source URL provided via props.

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

I also have a Movie component, which contains multiple URLs, each corresponding to a section of the movie. It also contains a position attribute, which acts like an iterator by 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 renders a Clip component and a "Next" button. When the Next button gets clicked, I want to update the position attribute and re-render the HTML5 video element using the next URL from sections.

As of now, when I hit Next the HTML5 video source tag updates, but the element continues playing the video from the previous URL. Can anyone help me figure out how to reset the video element?

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

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

1
  • Can you provide a jsfiddle?
    – Elon Zito
    Dec 23, 2016 at 15:01

5 Answers 5

193

Quick and dirty awnser: Add a key prop to <Clip> or <video>, e.g.:

function Clip({ url }) {
  return (
    <video key={url}>
      <source src={url} />
    </video>
  );
}

Recommended awnser: Trigger a load event for the video element whenever there's a new URL, e.g.:

function Clip({ url }) {
  const videoRef = useRef();

  useEffect(() => {    
    videoRef.current?.load();
  }, [url]);

  return (
    <video ref={videoRef}>
      <source src={url} />
    </video>
  );
}

Explanation: The video initially doesn'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. A new load event should be triggered for <video>.

The dirty answer works because when you change the key of a React element, React understands that's a whole new element. It then creates a new element in the DOM which naturally will have its own load event triggered on mount.

7
  • I needed to use createRef instead of useRef Oct 17, 2021 at 4:41
  • @DanielLizik, that's most certainly because you have a class component, correct? Oct 18, 2021 at 9:43
  • no, because I'm storing the video element ref in some 3rd party state lib. with useRef, the ref never changes, so even though source is updated correctly react continues to use the old ref; for me it created a strange bug where the video went black, but the audio from the previous video continued playing Oct 19, 2021 at 5:04
  • 2
    Use const videoRef = useRef<HTMLVideoElement>(null); for typescript. Oct 26, 2022 at 22:27
  • @RamonBalthazar Do you know if there is any performance/other benefits of using the second version compared to the first ? Oct 26, 2022 at 22:28
25

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>
  )
}
4
  • I tried using your code, but it didn't work either. I was never receiving an updatePosition unbound error. Dec 23, 2016 at 15:13
  • Of course that works, my bad, you bind with the arrow on the render. Something else is wrong then. Post a jsfiddle. You should still do it on the function instead though Dec 23, 2016 at 15:13
  • @Gundam194 that won't work cause you don't pass props in constructor. jsfiddle.net/d0exvp02/2. Changing the src doesn't seem to cause the video to start from the new url though Dec 23, 2016 at 15:57
  • @Gundam194 See answer now Dec 23, 2016 at 16:01
1

You can use the key attribute :

<video key={videoUrl} autoPlay width="100%">
  <source src={videoUrl} type="video/mp4"></source>
</video>

If the video's key attribute change, the video component will be re-mounted

0

Bind the URL in the src property of Video tag and not Source Tag

<video autoplay loop muted playsinline="true" webkit-playsinline="true" [src]="videoSrc" type="video/mp4">

0

Add a parent div to second video
My code:

{isMobile ? (
            <video
              autoPlay={true}
              loop
              className="moviles"
              muted
              playsInline
              poster="/totto/kids.png"
            >
              <source src="/totto/losmoviles.webm"></source>
              <source src="/totto/losmoviles.mp4"></source>
            </video>
          ) : (
            <div>
              <video
                autoPlay={true}
                loop
                className="moviles2"
                muted
                playsInline
                poster="/totto/portada.jpg"
              >
                <source src="/totto/moviles.webm"></source>
                <source src="/totto/moviles.mp4"></source>
              </video>
            </div>
          )}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.