How to play local video with React’s react-player library?

Sometimes, we want to play local video with React’s react-player library.

In this article, we’ll look at how to play local video with React’s react-player library.

How to play local video with React’s react-player library?

To play local video with React’s react-player library, we can add a file input that accepts a file.

Then we can convert the file object obtained to a file path that can be used with react-player.

For instance, we write:

import React, { useState } from "react";
import ReactPlayer from "react-player";

export default function App() {
  const [videoFilePath, setVideoFilePath] = useState(null);

  const handleVideoUpload = (event) => {
    const [file] = event.target.files;
    setVideoFilePath(URL.createObjectURL(file));
  };

  return (
    <>
      <input type="file" onChange={handleVideoUpload} />
      <ReactPlayer url={videoFilePath} width="100%" height="100%" controls />
    </>
  );
}

We define the videoFilePath state with useState.

Then we define the handleVideoUpload function that gets the file from the e.target.files object.

Next, we convert file to a video path that can be used with reacy-player with URL.createObjectURL.

Then we set url to videoFilePath.

Now when we select a video file from the file input, then we’ll see the video file displayed.

Conclusion

To play local video with React’s react-player library, we can add a file input that accepts a file.

Then we can convert the file object obtained to a file path that can be used with react-player.