James Morgan

Musings from the Frontend 🚀

React: Tidy Up Components with Property Initializers

Using ES6 classes to write React components has the drawback of requiring us to bind custom methods inside the constructor:

class App extends Component {
  constructor() {
    super()
    this.state = {
      data: []
    }
    this.fetchData.bind(this)
  }
}

We can make this a little less verbose using ES7+ property initializers, allowing us to drop the constructor entirely and declare state directly. Property initializers are bound to the class instance and not the prototype.

class CounterApp extends Component {
  state = {
    data: []
  }
}

Using arrow functions for our methods, we can ensure that this has the correct lexical binding and refers to the component itself:

fetchData = () => {
  this.setState({ data: response })
}

To get this compiled correctly, you'll have to adjust your Babel settings:

npm install --save-dev babel-plugin-transform-class-properties

.babelrc

{
  "plugins": [
    ["transform-class-properties"]
  ]
}

Now that's a squeaky 🛁 component. Treat yourself. 🍺 🌮