1

I have done this before in a react project.

const [formState, setFormState] = useState({ username: '', password: '', });

const handleInputChange = (e)=>{
    if(e.target.name==="username"){
        setFormState({...formState, username:e.target.value })
    }
    if(e.target.name==="password"){
        setFormState({...formState, password:e.target.value })
        }
    }

My two input elements had the onChange={handleInputChange} to update input value.

Now I have a form that has numerous inputs. And I want a code that can update the input based on the input name. something like this.

const handleInputChange=(e)=>{
    const inputName = e.target.name;
    const value = e.target.value;
    setFormState({...formState, inputName:value })
   };

I need help on that please

mykoman
  • 1,715
  • 1
  • 19
  • 33

3 Answers3

2

Just put inputName inside [ ]

const handleInputChange=(e)=>{
    const inputName = e.target.name;
    const value = e.target.value;
    setFormState({...formState, [inputName]:value })
   };
HermitCrab
  • 3,194
  • 1
  • 11
  • 10
1

ES2015 allows you to create a computed property name on an object by using the following syntax:

const a = { [someKeyName]: 'myValue' }

so you could write:

const handleInputChange = (e) => {
  setFormState({...formState, [e.target.name]: e.target.value })
};

There is a great answer dealing with this here: Creating object with dynamic keys

It also notes to take care when considering where this syntax will be used. Make sure it is supported in the browsers you intend to support. According to the MDN docs here, it wouldn't be usable in IE unless transpiled.

Shrubs
  • 41
  • 4
0

You can make input name dynamic like this

const handleInputChange=(e)=>{
  const inputName = e.target.name;
  const value = e.target.value;
  setFormState({...formState, [inputName]:value })
};
iamwebkalakaar
  • 358
  • 1
  • 9