Matthew Matthew - 1 year ago 180
React JSX Question

Why set a React Component's state outside of the constructor?

So I just downloaded source code from a React framework, and I'm getting this error in Terminal:

ERROR in ./src/components/TextEditor.js
Module build failed: SyntaxError: Unexpected token (24:8)

22 |
23 | // Set the initial state when the app is first constructed.
> 24 | state = {
| ^
25 | state: initialState
26 | }
27 |

My question is, why do people set a React Component's state like this? What's the benefit if it'll error for some people? Also, is there a Babel preset or plugin I can get to prevent this error?

This is how I usually set a component's state, and from what I've seen, this is conventional:

constructor() {
this.state = {
state: initialState

For the record, this is the entire document:

// Import React!
import React from 'react'
import {Editor, Raw} from 'slate'

const initialState = Raw.deserialize({
nodes: [
kind: 'block',
type: 'paragraph',
nodes: [
kind: 'text',
text: 'A line of text in a paragraph.'
}, { terse: true })

// Define our app...
export default class TextEditor extends React.Component {

// Set the initial state when the app is first constructed.
state = {
state: initialState

// On change, update the app's React state with the new editor state.
render() {
return (
onChange={state => this.setState({ state })}


Answer Source

The first example is using class properties which is not part of the ES6 spec. You can use them with babel using the stage-2 preset or the babel-plugin-transform-class-properties plugin module.

The usage is mostly a matter of preference and will produce the same result as your second example when transpiling with babel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download