Object-Destructing Use in React

Good morning, I was wondering what the point of the code on line 7 was. I’m aware of what object destructing is, and that is that I’m saying the first value of the this.state object is going to be called ‘markdown’. But why is he doing this?

Hello!

First of all, a little correction:

That’s not correct. It’s not the first value, it’s a property of the object. If the property markdown doesn’t exist on this.state, markdown will be undefined:

const obj = {
  theProp: 'value'
};

const { nonExistent } = obj;
const { theProp } = obj;

// Output: undefined
console.log(nonExistent);

// Output: "value"
console.log(theProp);

It’s not required for it to work; you could also write this.state.markdown instead and it would work, like this:

<textarea id="editor" value={this.state.markdown} />
2 Likes

For one property on the state object being used once, it’s really not necessary. Object destructuring like this is useful when you have multiple state values being used in your JSX, and rather than constantly this.state.name, this.state.email, this.state.avatar for things you’ll use in the template, you might

const {name, email, avatar} = this.state;

Now, as @skaparate has pointed out, note that i don’t know or care where in this.state we might have stored name or email - first or fifth or fiftieth, I’m accessing the property by name, not index. Arrays the position matters; objects, no.

2 Likes