Take your ES6 in React to the next level

You are already using ES6 and you love it because it makes your code more expressive and readable.

And it works perfectly with React!

Now that you know the basics you want more:

It’s time to take your ES6 skills to the next level!


Nested props destructuring

You already know you can extract variables from props in your React component with destructuring

const { user } = this.props;

But what if user is an object and you want to extract this.props.user.id to the variable id?

✨Next level ES6✨ You can use nested destructuring:

const { user: { id } } = this.props;

Now you have a variable id with the contents of this.props.user.id


Passing down all props

You already know you can pass down props to child components.

<MyChild shoe={this.props.shoe} cup={this.props.cup}/>

✨Next level ES6✨ passing down all props to a child component with spread syntax.

<MyChild {...this.props}/>

Now MyChild have access to both shoe, cup and all other props that the parent component has access to!


Destructuring props

You already know you can destructure props in arrow functions

const MyComponent = ({ shoe, car }) => /* do something */

But what if you also want access to the props object?

✨Next level ES6✨ It’s possible like this:

const MyComponent = ({ shoe, car, ...props }) => /* do something */

props now contain all props except shoe and car.


Functions as arguments

You already know you can pass arrow functions as arguments to other functions such as map and forEach

myList.map((a) => toUpperCase(a))

(You have to code toUpperCase yourself to make this code runnable)

✨Next level ES6 You don’t even need ES6✨ The code above can be written without even using an arrow function

myList.map(toUpperCase)

Much cleaner! When you only use one argument in the arrow function and just pass down that argument to a new function, you can write it like this.


List destructuring

You already know you can do destructuring of a list:

const [a, b, c] = list;

✨Next level ES6✨ Get the first item and the rest to two variables:

const [first, ...rest] = list;

Don’t miss out on more good tips like this – get on the email list