Learning React: Part 3

17 Jul 2018

this.state

Setting initial state

React component can access dynamic info in 2 ways: props and state

To make component have state, give the component a state property.

Property should be declared inside of a constructor method:
constructor (props){
super(props);
this.state={mood: 'decent'};
}

this.state should equal an object. Object represents the initial "state" of any component instance.

constructor and super are both features of ES6.

React components always have to call super in their constructors to be set up properly.

Methods should never be comma-separated!

Access a component's state

To read a component's state, use the expression
this.state.name-of-property

Just like this.props, you can use this.setState from any property defined inside of a component class's body.

Update state with this.setstate

this.setState( ) takes two arguments

  • An object will update the component's state
  • A callback (rarely need this)

this.setState() takes an object, and merges that object with the component's current state.

If there are properties in the current state that aren't part of that object, then those properties remain how they were.

Call this.setState from another Function

The most common way to call this.setState() is to call a custom function that wraps a this.setState() call.

  1. A user triggers an event (click event), triggered by clicking on a