A nice way to handle form states in ReactJS
ReactJS form states with useState hook.
Posted by Mohamed Hedeya in reactjs
April 24, 2021 - 1 min read
ReactJS form states with useState hook
example
{/* state */}const [person, setPerson] = useState({firstName:'', email:'', age:''})const [people, setPeople] = useState([])<inputtype='text'id='firstName'name='firstName'value={person.firsName}onChange={handleChange}/><inputtype='text'id='email'name='email'value={person.email}onChange={handleChange}/><inputtype='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:''})}}