0

I have an app which loads data from a json. That data could be a video, in which case it's rendered the next component:

export default function Video({ video }) {
  return (
    <>
      <video controls width="100%">
        <source src={require(video)} type="video/mp4" />
      </video>
    </>
  );
}

The param video has the path to the video, it's supossed to be located in a local folder on my app. When I try to render the component Video with a valid param, I obtain the next error:

Uncaught Error: Cannot find module 'static/content/sample_video.mp4'

Meanwhile, when I try to get the video directly from a string like this: `

        <source src={require("static/content/sample_video.mp4")} type="video/mp4" />


The video is rendered correctly. The parameter video has exactly the same string that I'm hardcoding in the require.

What should I do to render my video using the parameter?

2 Answers2

1

To solve the issue, you should trigger a load event for the video element whenever there's a new URL with a useEffect on a reference to the video element just like below.

import { useRef, useEffect } from "react";

export default function Video({ video }) {
  const videoRef = useRef();

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


  return (
    <>
      <video ref={videoRef} controls width="100%">
        <source src={require(video)} type="video/mp4" />
      </video>
    </>
  );
}

For more info see this post.

Samy Rahmani
  • 320
  • 1
  • 7
  • Yes using `.load()` is important but the main issue is first getting some file access, after that part, the code can move on to using the load command. – VC.One Oct 28 '22 at 14:41
0

I think there's a problem with the path that you have provided, check the folder structure or use the absolute path of the file, since I don't see any problems with your implementation