Tuesday, February 27, 2018

[React.js] Example of getInitialState in ES5 and constructor in ES6

getInitialState method provided by createReactClass() using ES5, to returns the initial state. This example is to create a Test component and initial a valuable in state named qty and assign it as 1000:
var Test = React.createClass({
  getInitialState: function(){
    return {qty:1000};
  },
  render:function(){
    return(
      <p>{this.state.qty}</p>
    );
  }
})
React.render(<Test/>, document.getElementById("root"));
for ES6, we use constructor do same thing:
class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {qty: 1000};
    // This line is important!
  }
  render() {
    return (
      <p>{this.state.qty}</p>
    );
  }
}
React.render(<Test/>, document.getElementById("root"));

Reference

https://reactjs.org/docs/react-without-es6.html
https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r

No comments :

Post a Comment