Day 66: React Course on Udemy

State

  • If we need to track state, we need to start off with a class component and not a stateless functional component.
  • The constructor method is a special function for ES6 classes in JavaScript.
  • Whenever an object is created via a class in JavaScript, JavaScript invokes the constructor function
  • React will invoke the constructor with the props and context of the Component
  • The super keyword invokes the constructor function defined by React.Component, which executes some necessary setup code for our Component
  • It is important to call super whenever we define a constructor function because if you would like to set a property or access "this" inside the constructor, you need to call super();
  • Fat arrow functions preserve the "this" context when they are called
// h2 tag with initial state - curly braces with JavaScript we want to evaluate
// if a component doesn't use props or context, its okay to not pass those along
// constructor method with props object
// super keyword and pass to it a value of props

class GuessAge extends React.Component {
  constructor(props) {
    super(props);
    // within constructor function we will set the state initially for our component
    // set this.state to a JS object with the property of age
    this.state = {
      age: 'Guess my Age'
    };
  }
  // this.setState to change our state
  // put in our age property that we're going to set to a new state of 30
  onButtonClick() {
    this.setState({
      age: '30'
    });
  }
  render() {
    return(
      <div>
        <h1>Guessing Game</h1>
        <h2>{this.state.age}</h2>
        <button.onClick={this.onButtonClick}>Reveal my Age</button>
      </div>
    );
  }
}
ReactDOM.render(
    <GuessAge/>,
    document.getElementById('app')
);