DEV Community

loading...

Discussion on: Controlled Form Inputs using React hooks

Collapse
jolouie7 profile image
Joseph Louie Author

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...

Forem Open with the Forem app