States in React Components - KatyaHorton/Udacity-React-practice GitHub Wiki

States in React Components

Props Attributes Immutable
State ? Mutable
  1. Components allow us to simplify the complexity of the State management to individual components.

  2. Large application = many small applications (which are actually just components).

  3. To add a State: add a state property who's value - object to our class.

  4. Each key in the object represents a distinct piece of State for this component.

  5. Access a state property: this.state.property.

  6. We separate:

  • look of the component (UI)
  • current state of the application

Because of the separation - UI is a function of an application state.

What we need to worry about:

  • what state the application is in
  • how does the UI change based on the state

Contacts (from the Temporary Contacts array paragraph) don't really belong to anything (temporary, right? ;))

This array contacts was just living as a variable react did not know about it.

To let React know about the contacts array we need to move it to a specific component itself.

We can add a state with contacts in it, so each time the state changes React will be aware of that change and change the UI accordingly.

Adding state property to our App class:

class App extends Component {
  state = {
   contacts: [
    {
    "id": "ryan",
    "name": "Ryan Florence",
    "email": "[email protected]",
    "avatarURL": "http://localhost:5001/ryan.jpg"
  },
  {
    "id": "michael",
    "name": "Michael Jackson",
    "email": "[email protected]",
    "avatarURL": "http://localhost:5001/michael.jpg"
  },
  {
    "id": "tyler",
    "name": "Tyler McGinnis",
    "email": "[email protected]",
    "avatarURL": "http://localhost:5001/tyler.jpg"
  }
]
}
  render() {
   return(
    <div>
     <ListContacts contacts={this.state.contacts}>
    </div>
)
}
}

Now our App copmponent manges that piece of state.

Note: do not initialise state with props

We don't pass the contacts array.

We access the state property from-inside of a component.

Rule:

If you use a piece of state in order to render some UI - the state should live inside a component somewhere.

⚠️ **GitHub.com Fallback** ⚠️