DEV Community

Discussion on: Controlled Form Inputs using React hooks

Collapse
 
sabbin profile image
Sabin Pandelovitch • Edited

Why do you use different state objects for each input?

This part of your code

const [name, setName] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // Everytime input changes we update the state
  const handleChange = (e) => {
    if (e.target.name === "name") {
      setName(e.target.value);
    } else if (e.target.name === "username") {
      setUsername(e.target.value);
    } else if (e.target.name === "email") {
      setEmail(e.target.value);
    } else if (e.target.name === "password") {
      setPassword(e.target.value);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("name: ", name)
    console.log("username: ",username)
    console.log("email: ",email)
    console.log("password: ",password)
  }
Enter fullscreen mode Exit fullscreen mode

Can be simplified to this

const [formData, setFormData] = useState({
    name:'',
    username: '',
    email: '',
    password: ''
});

const handleChange = ({ target:{ name, value }}) => {
    setFormData(prevData => ({
      ...prevData,
      [name]: value,
    }))
};

const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData)
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jolouie7 profile image
Joseph Louie

Your right, my code isn't the best. Thank you for sharing how you would do it! I've near seen someone do this before. Pretty cool

{ target:{ name, value }}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sabbin profile image
Sabin Pandelovitch • Edited

This is a feature of ES6, called destructuring.

const obj = { a: 10, b: 15, child: { c:10, d:11}};

const { a, b } = obj; // this will create 2 variables a and b with the value from object.a object.b
const { a: foo, b: bar } = obj; // this will create 2 variables foo which is a, and bar which is b. This is actually for renaming the variables so you don't have conflicts in case you have the same defined before

const { a, child: { c } } = obj; // It can work on nested objects too, in this case you get a and c variables
Enter fullscreen mode Exit fullscreen mode

So actually it can be used on function parameters as well

const obj = { a: 10, b: 15, child: { c:10, d:11}};

const fn = param => console.log(param.a, param.child.c);
//param can be deconstructed 
const fn = ({ a, child: { c }) => console.log(a, c);
Enter fullscreen mode Exit fullscreen mode

There is more to this than the examples above.

Documentation -> developer.mozilla.org/en-US/docs/W...