DEV Community

hasibulc
hasibulc

Posted on • Edited on

2

Destructuring Props in React

JavaScript ES6 introduced destructuring, which allows you to extract values from arrays, or properties from objects. Destructuring allows for fewer lines of code which improves readability (and helps developers be lazy efficient).


Speaking of being efficient, check this out:


Here is an example of a state object that might be passed down as props.

state = {
    displayArray: [],
    clicked: false,
    searchKey: ""
  }

In the past, I would have written the following to access the props:

let displayArray = props.displayArray
let clicked = props.clicked
let searchKey = props.searchKey

However, I can easily write those three lines as one line because I am accessing properties from the same object. In this case, the props object.

Destructured:

let { displayArray, clicked, searchKey } = props;

Another Example:

<Card>
    <img src={this.state.front ? this.props.pokemon.sprites.front : this.props.pokemon.sprites.back} alt=" "/>
    <div className="header">{this.props.pokemon.name}</div>
</Card>

Or

let name = this.props.pokemon.name
let sprites = this.props.pokemon.sprites

<Card>
    <img src={this.state.front ? sprites.front : sprites.back} alt=" "/>
    <div className="header">{name}</div>
</Card>

Destructured:

let { name, sprites } = this.props.pokemon;

<Card>
    <img src={this.state.front ? sprites.front : sprites.back} alt=" "/>
    <div className="header">{name}</div>
</Card>

Sources:

  1. Learn the basics of destructuring props in React
  2. Prefer destructuring from arrays and objects (prefer-destructuring)

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay