States in React Components - KatyaHorton/Udacity-React-practice GitHub Wiki
Props | Attributes | Immutable |
---|---|---|
State | ? | Mutable |
-
Components allow us to simplify the complexity of the State management to individual components.
-
Large application = many small applications (which are actually just components).
-
To add a State: add a
state
property who's value - object to ourclass
. -
Each key in the object represents a distinct piece of State for this component.
-
Access a state property:
this.state.property
. -
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.
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>
)
}
}
Note: do not initialise state
with props
We don't pass the contacts
array.
We access the state
property from-inside of a component.
If you use a piece of state in order to render some UI - the state should live inside a component somewhere.