bradxr
12/13/2018 - 11:35 AM

05 - Understanding and Using State

Understanding and Using State

  • State only works on stateful (class-based) compponents
  • State is a reserved keyword
  • State is managed from inside the component
  • If the state changes, React will update the DOM
  • State can't be changed directly
  • Must use this.setState() to manipulate state
    • takes an object as an argument
  • Updates will merge

Code Example - Introducing State

import React, {Component} from 'react';

class App extends Component {
  // SETTING UP STATE
  state = {
    persons: [
      {name: 'Brad', age: 22},
      {name: 'Ryan', age: 21}
    ]
  }
  
  render() {
    return(
      ...
    )
  }
}

export default App;

Code Example - Accessing State

import React, {Component} from 'react';

class App extends Component {
  // SETTING UP STATE
  ...
  
  render() {
    return(
      <div>
        // ACCESSING STATE
        <Person name={this.state.props.persons[0].name}
          age={this.state.props.persons[0].age} />
        <Person name={this.state.props.persons[1].name}
          age={this.state.props.persons[1].age} />
      </div>
    )
  }
}

export default App;

Code Example - Manipulating State

import React, {Component} from 'react';

class App extends Component {
  // SETTING UP STATE
  ...
  
  // EVENT HANDLER
  switchNameHandler = () => {
    // MANIPULATING STATE
    this.setState({
      persons: [
        {name: 'John', age: 20},
        {name: 'Adam', age: 22}
      ]
    })
  }
  
  render() {
    return(
      <div>
        // EVENT LISTENER
        <button onClick={this.switchNameHandler}>Switch Names</button>
        ...
      </div>
    )
  }
}
export default App;