Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
  super();
  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 (
      <Editor
        state={this.state.state}
        onChange={state => this.setState({ state })}
      />
    )
  }

}
like image 824
Matthew Avatar asked Aug 27 '16 19:08

Matthew


1 Answers

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.

https://babeljs.io/repl/#?evaluate=true&lineWrap=false&presets=react%2Cstage-0&experimental=false&loose=false&spec=false&code=%2F%2F%20Code%20goes%20here%0Aclass%20First%20%7B%0A%20%20state%20%3D%20%7B%0A%20%20%20%20value%3A%20true%0A%20%20%7D%0A%7D%3B%0A%0Aclass%20Second%20%7B%0A%20%20constructor%20()%20%7B%0A%20%20%20%20this.state%20%3D%20%7B%0A%20%20%20%20%20%20value%3A%20true%0A%20%20%20%20%7D%3B%0A%20%20%7D%0A%7D%3B%0A

like image 174
ryanjduffy Avatar answered Oct 21 '22 19:10

ryanjduffy