React trick 2

Michael Minchang Kim·2020년 5월 31일
0

wecode

목록 보기
22/22

how to handle cases where you have to recieve value through props but the data hasn't loaded yet, so the jsx renders without proper data.

<img
 src={
       this.props.data &&
       (image 
       ? this.props.data.front 
       : this.props.data.back)
     }
     onMouseOver={() => this.changeImage("image")}
     onMouseLeave={() => this.changeImage("image")}
     alt="item"
/>

As you can see in the code above, there is a && after this.props.data. This && tells react to wait until this.props.data is not Null.
The code in the back of the && changes the image source depending on the boolean value of image.
If the props hadn't loaded yet, then the jsx would render without an image source.

Another thing you can notice is that the variable image is being used without any declaration or this.state. or this.props. infront of it.
This is made possible through a const declaration at the beginning of the render.

const { image } = this.state;

This declaration creates a const variable of the name image with the value of this.state.image

profile
Soon to be the world's Best programmer ;)

0개의 댓글