A nice way to handle form states in ReactJS

A nice way to handle form states in ReactJS

Subscribe to my newsletter and never miss my upcoming articles

ReactJS form states with useState hook

example

{/* state */}
const [person, setPerson] = useState({firstName:'', email:'', age:''})
const [people, setPeople] = useState([])

<input
   type='text'
   id='firstName'
   name='firstName'
   value={person.firsName}
   onChange={handleChange}/>

<input
   type='text'
   id='email'
   name='email'
   value={person.email}
   onChange={handleChange}/>

<input
   type='text'
   id='age'
   name='age'
   value={person.age}
   onChange={handleChange}/>

for handleChange

handleChange(e)=> {
 const name = e.target.name;
 const value = e.target.value;
 setPerson({...person, [name]:value});
}

for the handleSubmit

const handleSubmit(e)=> {
   e.preventDefault();
   if(person.firstName && person.email && person.age) {
      const newPerson = {...person, id: new Date().getTime().toString()};
      setPeople([...people, newPerson]);
      setPerson({firstName:'', email:'', age:''})

   }
}
 
Share this
Proudly part of