I try to upload a video in react-js and preview but i am failed, how to pass the fi variable to the url section my code like
import {useState} from 'react';
import ReactPlayer from 'react-player';
function Video(props) {
const [file,setFile] = useState( null );
const onInputValue = (e) => {
var fi = URL.createObjectURL(e.target.files[0])
console.log(fi);
};
return (
<div>
<form method="post" action="#" id="#">
<input type="file" onChange={onInputValue}/>
<button>Upload</button>
</form>
<ReactPlayer
controls
url={fi}
id="videoz" />
</div>
);
}
export default Video;
i do this way but show error in fi variable error
src\components\Video.js
Line 22:18: 'fi' is not defined no-undef
how to solve this issue, i am new in react!
CodePudding user response:
You var
fi, is scoped to the function. It is not visible outside onInputValue
. Hence the error.
The variable you want to use, should cause a rerender when it is changed. State is the logical solution. You can use a state variable with useState which will be updated.
function Video(props) {
const [file,setFile] = useState( null );
const [fi,setFi] = useState('');
const onInputValue = (e) => {
var newFi = URL.createObjectURL(e.target.files[0])
console.log(newFi);
setFi(newFi);
};
return (
<div>
<form method="post" action="#" id="#">
<input type="file" onChange={onInputValue}/>
<button>Upload</button>
</form>
<ReactPlayer
controls
url={fi}
id="videoz" />
</div>
);
}
CodePudding user response:
I recommend that you save your fi inside a state, so then you can pass it to your ReactPlayer
, which then would need a validation to see if it's not null.
import { useState } from 'react';
import ReactPlayer from 'react-player';
function Video(props) {
const [file, setFile] = useState(null);
const [fi, setFi] = useState(null);
const onInputValue = (e) => {
setFi(URL.createObjectURL(e.target.files[0]));
console.log(fi);
};
return (
<div>
<form method="post" action="#" id="#">
<input type="file" onChange={onInputValue} />
<button>Upload</button>
</form>
<ReactPlayer controls url={fi} id="videoz" />
</div>
);
}
export default Video;