Home > Net >  react-hook-form provides a syntax that I've never seen before, I would like to know the name of
react-hook-form provides a syntax that I've never seen before, I would like to know the name of

Time:10-01

I would like to know what syntax this is: enter image description here

This is called object destructuring. You can learn more about it here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Explanation

The input element has many properties, like onChange, onBlur, name, ref... etc.

And the register function, when called by passing an argument, returns all of these properties that I've mentioned above.

So, this:

const { onChange, onBlur, name, ref } = register('firstName');

Creates four variables (const) that can be used later in my element

<input 
   onChange={onChange}
   onBlur={onBlur}
   name={name}
   ref={ref}
/>

Now, let's say that I had a function that printed all of the values that register('firstName') had.

const printFunction = (onChangeParameter, onBlurParameter, nameParameter, refParameter) => {
    console.log(onChangeParameter, onBlurParameter, nameParameter, refParameter)
};

But I don't want to call it extracting each variable at a time and then putting it in the function (like this):

const { onChange, onBlur, name, ref } = register('firstName');
printFunction(onChange, onBlur, name, ref);

So I can just DESTRUCTURE register('firstname') inside the function.

printFunction(...register('register'));

And essentially get the same result, but much quicker.

This is what is happening in the input element. You're calling a function that returns multiple things, and grabbing each of those things and putting it into the input element.

  • Related