Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the constructor still needed in React with autobinding and property initializers

I am refactoring an es6 class based React component that uses the normal constructor, and then binds methods, and defines state/attributes within that constructor. Something like this:

class MySpecialComponent extends React.Component {
  constructor(props) {
   super(props)
   this.state = { thing: true }
   this.myMethod = this.myMethod.bind(this)
   this.myAttribute = { amazing: false }
  }

  myMethod(e) {
   this.setState({ thing: e.target.value })
  }
}

I want to refactor this so that I am autobinding the functions, and using property initializers for the state and attributes. Now my code looks something like this:

class MySpecialComponent extends React.Component {
  state = { thing: true }
  myAttribute = { amazing: false }


  myMethod = (e) => {
   this.setState({ thing: e.target.value })
  }
}

My question is, do I still need the constructor? Or are the props also autobound? I would have expected to still need the constructor and included super(props), but my code seems to be working and I'm confused.

Thanks

like image 921
Max Millington Avatar asked Jun 21 '17 19:06

Max Millington


People also ask

Is it necessary to use constructor in React?

Note: If you neither initialize state nor bind methods for your React component, there is no need to implement a constructor for React component.

Can we use state without constructor in React?

You can also use state in React function components (without a constructor), but using higher-order components or render prop components.

What is the difference between using constructor vs getInitialState in React?

The constructor and getInitialState both in React are used to initialize state, but they can't be used interchangeably. The difference between these two is we should initialize state in the constructor when we are using ES6 classes and define the getInitialState method when we are using React. createClass (ES5 syntax).

Do you need to add key property on Reactjs elements?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.


1 Answers

From my understanding, you don't need to type out a constructor at all when using class properties (as in your second code example). The accepted answer states that you do need one if you "need to reference the props in your initial state object," but if you're using said class properties, then you're probably using Babel to transpile it, in which case a constructor is used, it's just being done behind the scenes. Because of this, you don't need to add a constructor yourself, even if you are using props in state.

See this aricle for better examples and a better explanation.

like image 68
Christian Jensen Avatar answered Sep 21 '22 19:09

Christian Jensen