Peter Zacharias Peter Zacharias - 9 months ago 46
React JSX Question

What does this render method do: const {images, selectedImage} = this.state;?

I'm doing a simple tutorial on react/ redux and I do not understand why we have to, in the render() method, do


const {images, selectedImage} = this.state;


I understand that we need to assign the previously defined variables to the constructor, so it becomes part of our component state and is not just a variable floating around in our component only, but I do no get why we cannot just access them directly in the render method later? I also do not understand why they are defined as constants? I also don't get why they are assigned to state and why they have parentheses aroudn them? Thanks a lot for your help

import React, {Component} from 'react'

const flickrImages = [
"https://farm2.staticflickr.com/1553/25266806624_fdd55cecbc.jpg",
"https://farm2.staticflickr.com/1581/25283151224_50f8da511e.jpg",
"https://farm2.staticflickr.com/1653/25265109363_f204ea7b54.jpg",
"https://farm2.staticflickr.com/1571/25911417225_a74c8041b0.jpg",
"https://farm2.staticflickr.com/1450/25888412766_44745cbca3.jpg"
];

export default class Gallery extends Component {
constructor(props) {
super(props);
this.state = {
images: flickrImages,
selectedImage: flickrImages[0]
}
}

handleThumbClick(selectedImage) {
this.setState({
selectedImage
})
}

render() {
const {images, selectedImage} = this.state; // why do we have to do this? And why does this need to be a constant?
return (
<div className="image-gallery">
<div className="gallery-image">
<div>
<img src={selectedImage} />
</div>
</div>
<div className="image-scroller">
{images.map((image, index) => (
<div key={index} onClick={this.handleThumbClick.bind(this,image)}>
<img src={image}/>
</div>
))}
</div>
</div>
)
}
}


PS: if you can suggest a better title for this question please let me know, i was not sure what to call it, and I'm sure there's a better name the sort of thing that's being done here

Answer Source

It's called object destructuring.

It assigns this.state.images to the local constant images and this.state.selectedImage to the local constant selectedImage.