0

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

2
  • It's saying "give me a property target of the argument object, and then give me the property value of the target object". I don't think it is particularly readable. Commented Dec 7, 2021 at 12:30
  • onChange expects event object as a parameter. Event object has target property which, in turn, has value property. So, essentially, you may think of destructuring function parameter as a way of expressing (through the shape of the input object) exact nested property, which becomes a variable with corresponding name inside function body. Commented Dec 7, 2021 at 12:31

2 Answers 2

1

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} />;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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' } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.