Search code examples
htmlreactjsvideo

Video element renders blank, no video and no errors


I can not for the life of me figure out why the video element (photoed at the bottom) is not showing the video that I am trying to upload.

File structure is:

app-name/
         App.js
         src/
             components/
                    VideoForm.js
                    VideoList.js
                    VideoItem.js
             media/
                    poppies.mp4

import "./App.css";
import VideoForm from "./components/VideoForm";
import VideoList from "./components/VideoList";

function App() {
  const [videos, setVideos] = useState([]);

  return (
    <div className="App">
      <VideoForm videos={videos} setVideos={setVideos} />
      <VideoList videos={videos} />
    </div>
  );
}

export default App;
import React from "react";

const VideoForm = ({ videos, setVideos }) => {
  const handleChange = (event) => {
    event.preventDefault();
    setVideos([
      ...videos,
      { name: event.target.files[0].name, type: event.target.files[0].type },
    ]);
  };

  return (
    <div>
      <input type="file" onChange={handleChange} />
    </div>
  );
};

export default VideoForm;
import React from "react";
import VideoItem from "./VideoItem";

const VideoList = ({ videos }) => {
  console.log("videoList", videos);

  return (
    <div id="video-container">
      {videos &&
        videos.map((video) => (
          <VideoItem key={video.name} file={video.name} type={video.type} />
        ))}
    </div>
  );
};

export default VideoList;
import React from "react";

const VideoItem = ({ file, type }) => {

  const videoPath = "../media/" + file;

  return (
    <div>
      <video controls>
        <source src={videoPath} type={type} />
      </video>
    </div>
  );
};

export default VideoItem;

Can not for the life of me find out why the video shows up blank with a 0:00 timestamp. The video is not corrupt. I can watch it in vscode. I changed the permissions too. It shows up blank for Firefox and Chrome and Brave.

blank video element


Solution

  • Turns out I needed to place it in the /public directory and then to NOT add public to the filepath, because it is assumed. When you're running your React application, the public directory is already being served directly from the root URL, so you don't need to include the ../public/ part in your video path. For it to work, all you need to do is to provide the filename, once it is in the /public directory.

    import React from "react";
    
    const VideoItem = ({ file, type }) => {
    
         // Removed the videoPath variable
    
      return (
        <div>
          <video controls>
            <source src={file} type={type} /> // place in file prop as is
          </video>
        </div>
      );
    };
    
    export default VideoItem;