How To Set File Object In State With React Hooks?
I want to add to state and file object which I'm getting from input type file, and my problem is that I cannot update state with this:
currentTarget.files[0]
I'm getting this error:
DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
const [data, changeData] = useState({
name: '',
surname: '',
cv: '',
});
HandleChangeEvent for getting data
const handleChangeData = ({ currentTarget }, key) => {
if (currentTarget.type === 'file') {
const files = currentTarget.files[0];
changeData((prevState) => {
console.log(prevState);
return { ...prevState, [key]: files };
});
} else {
// Validate property
const val = currentTarget.value;
const errorMessage = validateProperty(currentTarget);
if (errorMessage) errors[currentTarget.name] = errorMessage;
else delete errors[currentTarget.name];
changeData((prevState) => {
return { ...prevState, [key]: val };
});
}
};
I want to get property files
from input field and send it to backend
Answer
It looks like you are trying to pass a 'value' prop to the file input.
<input type="file" value="???" />
In React
(as well as in html/js
) file inputs values can only be set by a user, and not programmatically (due to security reasons).
You should work with your file input as with an uncontrolled component
https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag
Solution: Set the state's value from the file input (if you really need it), but don't set the input's value from state. Just find another way to show that the file has already been chosen in UI.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM