React class constructor error

Asked

Viewed 174 times

2

I have the following error when I try to use Component in this way.

client?cd17:119 ./src/App/Components/AddNote.js
Module build failed: SyntaxError: super() outside of class constructor (9:4)

   7 | const FormText = React.createClass({
   8 |   constructor(props) {
>  9 |     super(props)
     |     ^
  10 |     this.state = { title: '', note: ''}
  11 | 
  12 |     this.handleChange = this.handleChange.bind(this)

 @ ./src/App/App.js 17:15-46
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index

But if I use this other way I can pass normally the properties to constructor. Can anyone tell me what mistake I’m making?

class AddForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {title: '', note: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({title: event.target.value, note: event.target.value});
  }

  handleSubmit(event) {
    alert('Os dados foram submetidos' + this.state.title +' e '+ this.state.note);
    event.preventDefault();
  }

1 answer

2


The difference is that one is Javascript valid in ES5 and another is code ES6. In other words, at the beginning when React was launched it used a lot of code compatible with ES5 (Ecmascript 5) and that did not need to be transposed. Later Babel and other transpilators began to convert ES6 code with newly inserted classes in the language and began to adopt class syntax, leaving the initial, Object.

Thus, in React the ES5 style with objects is not used super() nor the this.state = {}. That’s why there are methods that do this:

  // defenir Tipos de valores
  propTypes: {
    initialValue: React.PropTypes.string
  },
  // defenir valores antes do estado mudar
  defaultProps: {
    initialValue: ''
  },
  // Receber as primeiras props
  getInitialState: function() {
    return {
      text: this.props.initialValue || 'placeholder'
    };
  },

In ES6 syntax that would be simply:

super(props);
this.state = {algo: props.algo};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.