ganesh kaspate
ganesh kaspate

Reputation: 2685

Object destructuring in the function parameters in react

I am new to the ES6 Features, I have following code,

I have following component.

    function ToDo() {
    
      const onChange = ({target: {value}}) => {
        console.log(target)
      }
     
    
    return (
    <input type="text" onChange={onChange} value={item.text} /> 
    )
}

Here I did not understand the part of object destructuring in the onChange function. Where it should have been like event.target.value

Thanks

Upvotes: 0

Views: 2511

Answers (2)

olaven
olaven

Reputation: 186

Object destructuring

Object destructuring is just syntactic sugar for extracting values from an object. See the following:

const person = {name: "Peter", computer: {model: "macbook", ram: 16}}
const { name } = person; // this would give "Peter"
const { computer } = person; // this would give {model: "macbook", ram: 16}

// now the tricky part. Just re-uses the same destructuring-syntax twice :) 
const { computer: { model }} = person; 
console.log(model) // gives "macbook"

// the lines above are essentially the same as this: 
const { computer } = person; // first getting computer 
const { model } = computer; // then getting the model
console.log(model); //also gives "macbook"

Your code

If you log value instead of target, you should see the value of event.target.value.

function ToDo() {
  const onChange = ({ target: { value } }) => {
    console.log(target, value);
  };

  return <input type="text" onChange={onChange} value={item.text} />;
}

Upvotes: 1

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

here const onChange = ({target: {value}})=> ... on change argument is event object that you have extracted target from event, since target itself is an object, you then extracted value from target.

event looks this shape: { ..., target: { ..., value: 'some value' } }

Upvotes: 0

Related Questions