ES6 and React.js: Pass props to components using comment-like code

Comments usually help you, but they can lie. Sometimes that lie will lead you down a wild goose chase to find something that doesn't exist. The JavaScript engine cannot validate comments so they have to always be taken at face value. Use them only when you need to. Luckily, ES6 brings some nice features to cleanly avoid comments when passing props into components.

Let's look at a small example. Not all of data in our ParentComponent gets passed into UserProfile, its child component. But at the same time, we want to make our code as readable and expressive as possible. There are multiple ways to approach this.

import React, { Component } from 'react'
// ParentComponent props
// this.props = {
//   name: 'Andrew',
//   description: 'A person',
//   imageUrl: 'http://www.somewebsite.com/profile_picture.jpg',
//   age: 26,
//   height: '180cm',
//   birthday: '10.18.1990',
//   favoriteColor: 'blue',
//   martialStatus: 'single'
// }
export default class ParentComponent extends Component {
  render() {
    return (
      <div>
        <UserProfile/> {/*how should we pass the props we need in?*/}
      </div>
    )
  }
}

class UserProfile extends Component {
  render() {
    return (
      <div>
        { this.props.name }
        { this.props.description}
        birthday: { this.props.birthday }
        martial status: {this.props.martialStatus}
      </div>
    )
  }
}

Option 1: Pass in each prop individually (lengthy)

<UserProfile
  birthday={this.props.birthday}
  name={this.props.name}
  description={this.props.description}
  martialStatus={this.props.martialStatus}
/>

Your knee-jerk, non-ES6 choice. It's expressive, but quite lengthy. We can make it more concise with ES6.

Option 2: Use the spread operator on this.props in component (ambiguous)

//using birthday, name, description, and martialStatus
<UserProfile {...this.props} />

Very concise, but almost no expressiveness. It relies on a comment that may be outdated. Not only that, but you're passing in a lot of extra data in. Don't go out of your way to confuse you from the future.

Option 3: Object destructure assign this.props, use object literal shorthand to make new object, and spread the object into the component (concise and expressive)

const { birthday, name, description, martialStatus } = this.props
const userProfileProps = { birthday, name, description, martialStatus }
<UserProfile {...userProfileProps} />

Sounds like a lot of work, but it's worth it. This style is just as expressive as option 1 and as concise as it gets. Good code speaks for itself.

Comments

Popular posts from this blog

Contrasting var and ES6s new declarations: let and const

Modularity vs. Abstraction. Which is More Important?

Unit testable components pt.3: Testing components