react; state;

react is based on components 

Each component has props

props are read only values passed into a component from a parent

state

...used to store data that is changes over time

state is ...

...used to store values local only to that component that can be updated to re-render the page

state is ...

basic state

class Person extends React.Component {
   state ={
     age:36
   }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>I am {this.state.age} years old.</h2>
      </div>
    );
  }
}

  

updating state

state is immutable

basic example

class Person extends Component{
  state = {
    age: 36
  }

  haveBirthday = () => {
      this.setState({
        age: this.state.age + 1,
      })
  }

  render() {
    return (
      <div>
	You are {this.state.age}
	<button onClick={this.haveBirthday}>Have Birthday</button>
      </div>
    );
  }
}

  

add items to state

class Person extends Component{
  state = {
    age: 36
  }

  haveBirthday = () => {
      this.setState({
        age: this.state.age + 1,
        isBirthday: true
      })
  }

  render() {
    return (
    <div>
      You are {this.state.age}
      <button onClick={this.haveBirthday}>Have Birthday</button>
    </div>
    );
  }
}

  

life cycle

react - state

By Mark Dewey

react - state

  • 283