I am currently trying to play a video on local host in react.js. I am using the react-player module to create a video player component. I am able to play videos using urls such as youtube and facebook links but I am unable to use local videos using the filepath. I read through all of the documentation on github for the module but I was unable to find an answer, which is why I am here asking you this question. Below is my code :
import React, { Component } from 'react'
import ReactPlayer from 'react-player'
class Video extends Component {
render () {
return (
<div className='player-wrapper'>
<ReactPlayer
className='react-player fixed-bottom'
url= 'M_03292018202006_00000000U2940605_1_001-1.MP4'
width='100%'
height='100%'
controls = {true}
/>
</div>
)
}
}
export default Video;
In order to play local video in React, you need to first upload the video file. Once the file is uploaded, you need to transform it into a playable URL by using Javascript. Now that we know what is needed, let's have a look at the code. We'll have a file input that can be used to upload a video.
Go inside the React file where you want to import your video, add this line import MyVideo from "../content/videos/my-video. mp4" anywhere, as long as it's below your import React from 'react' import.
To display an image from a local path in React:Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
you have to create video object URL.
import React, { useState } from "react";
import ReactPlayer from "react-player";
const [videoFilePath, setVideoFilePath] = useState(null);
const handleVideoUpload = (event) => {
setVideoFilePath(URL.createObjectURL(event.target.files[0]));
};
....
<input type="file" onChange={handleVideoUpload} />
...
<ReactPlayer url={videoFilePath} width="100%" height="100%" controls={true} />
With a Create React App (short CRA) you could place your video files in the public folder e.g. in a subfolder videos
. Then you can access that static file as you did it in your code.
CRA will just copy the files to the final static page as mentioned in the docs.
If you don't use a CRA setup you need to copy your video to the final bundle e.g. by using Webpack.
import React, { Component } from 'react'
import ReactPlayer from 'react-player'
class Video extends Component {
render () {
return (
<div className='player-wrapper'>
<ReactPlayer
className='react-player fixed-bottom'
url= 'videos/demo_video.MP4'
width='100%'
height='100%'
controls = {true}
/>
</div>
)
}
}
export default Video;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With