Saturday, November 16, 2019

Destructuring in React - what is that?

Destructuring in React


Wondering what destructuring in React is?

It is taking a certain value out of the many other values stored together.

Or, go back to my favorite way of explaining things: comparison!


Imagine you have a basket full of eggs, and each egg has a name written on it. 
So when you want an egg, you just want this precise egg, not any egg from the basket.
Therefore, you take it out and sort it by alphabet. Every time you need a certain egg from the basket, you don't need to take out all the eggs one by one. You know exactly where to look to get
the egg with the right name!
Photo credit: someone from Pinterest

Destructuring is similar. 
It means taking a certain prop out of the basket of props so you can use it whenever you like.
For example, your prop (among others) is:

 name: 'Adam'


In case we are in a class based component, before destructuring, we will access this prop like this: this.props.name. And than we do the destructuring: 

const {name} = this.props;


and now we can use {name} every time we want to access this prop.

On the other hand, if we are in a functional component, our prop will look like this:

name: 'Adam'
and we access it like this: props.name

now destructuring in functional component will look like this:

const {name}  =  props;

Because we don't have problems with "this" keyword in functional components. This little "issue" is related to class based components only. 

Now if we are in our class based components where we want to pass props to our child component (and of course we have state), how do we do the destructuring then?
we do it like this:

const {name} = this.state; (because we are in the class that we refer to as "this". No worries, I will write more about "this" in one of my next posts.
I hope you managed to grasp the point here: getting a certain thing from a bunch of things without breaking a sweat.

Thanks for reading, stay tuned!

No comments:

Post a Comment

Props: how do we pass them?

Props, how do we pass them? Hey people, it's me again. This time I am trying to share some tips on passing the props in React. Last ...