Updating source URL on HTML5 video with React

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.

Leave a Comment