Error in class constructor in React

2

I get the following error when I try to use the component 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 normally pass properties to constructor. Can anyone tell me what error 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();
  }
    
asked by anonymous 30.03.2017 / 15:17

1 answer

2

The difference is that one is JavaScript valid in ES5 and another is ES6 code. That is, at the beginning when React was released, a lot of code compatible with ES5 (ECMAScript 5) was used and it did not need to be transpiled. Later Babel and other transpilators began converting ES6 code with newly inserted Classes into the language and adopted the class syntax, leaving the initial, Object.

So, in React in style ES5, objects do not use super() nor this.state = {} . This is where we go about 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 this would simply be:

super(props);
this.state = {algo: props.algo};
    
30.03.2017 / 16:04