An experienced software developer with a strong background in developing award-winning web and mobile applications for diverse clients with 6+ years of industry experience.
We can do better using an object, spread operator and computed properties instead of bunch of ifs.
This approach is more scalable and even allow sending the object as JSON easily.
importReact,{useState}from"react";import"./styles.css";exportdefaultfunctionApp(){// Where our state is being storedconst[form,setForm]=useState({name:'',username:'',email:'',password:''})// Everytime input changes we update the stateconsthandleChange=(e)=>{setForm(prevForm=>({...prevForm,[e.target.name]:e.target.value}))};consthandleSubmit=(e)=>{e.preventDefault();console.log('form: ',form)}// The value will be based on the statereturn(<divclassName="App"><h1>Controlled input</h1><formonSubmit={handleSubmit}><div><label>name</label><inputtype="text"name="name"value={form.name}onChange={handleChange}></input></div><div><label>username</label><inputtype="text"name="username"value={form.username}onChange={handleChange}></input></div><div><label>email</label><inputtype="email"name="email"value={form.email}onChange={handleChange}></input></div><div><label>password</label><inputtype="password"name="password"value={form.password}onChange={handleChange}></input></div><buttontype="submit">Submit</button></form></div>);}
Yea, my approach wasn't the best. I was justing so used to seeing my state separated like that, that I just kept doing it. Your code is so much better and much more scaleable! Thank You for sharing! I'll be doing this from now on!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
We can do better using an object, spread operator and computed properties instead of bunch of ifs.
This approach is more scalable and even allow sending the object as JSON easily.
Yea, my approach wasn't the best. I was justing so used to seeing my state separated like that, that I just kept doing it. Your code is so much better and much more scaleable! Thank You for sharing! I'll be doing this from now on!