Home > Net >  Handle multiple input field (including file field) using one event handler in react js
Handle multiple input field (including file field) using one event handler in react js

Time:01-01

I want to handle my all input field including file field using one event handler. Is that possible in react js? I know how to handle multiple text field using one event handler but cant work with file field. My previous code was like that.

const changeHandler = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs({
...inputs,
[name] : value,
});
}
 const {name, email} = inputs;
  const formData = new FormData()
  formData.append('name', name)
  formData.append('email', email)

CodePudding user response:

You could deconstruct the files and do a check whether or not the file input was used.

const changeHandler = ({ target }) => {
  const { name, value, files } = target;
  if (files) {
    setInputs({
      ...inputs,
      [name]: files[0],
    });
    return;
  }
  setInputs({
    ...inputs,
    [name]: value,
  });
};

CodeSandbox : https://codesandbox.io/s/gallant-cherry-4vufyr?file=/src/App.js

Note that this example only saves a single file.

You could also do a conditional in place of an if statement which is saying: If there is a file, set the file else set the value.

  const anotherHandler = ({ target }) => {
    const { name, value, files } = target;
    setInputs({
      ...inputs,
      [name]: files ? files[0] : value
    });
  };
  • Related