Repository navigation
React Component State API
Howie Reith edited this page Sep 27, 2019
·
10 revisions
The purpose of this section is to build competency with the React State API by
examining an example application.
Navigate to the
state-apidirectory and run the following commands:npm install npm startOnce the app loads, play the
Name that Pirategame to familiarize yourself with the appOpen the
state-apifolder using your favorite editor (your favorite editor should be vim, but anyway...) and familiarize yourself with theReactcomponents
Important Concepts:
-
All state is maintained in
React.Componentstateandprops. Therefore, state is localized to each component.-
propsare immutable -
stateis mutable.
-
-
While
stateis mutable, the means of mutation is constrained to thesetStatefunction.-
setStateinforms the component and its children to re-render based on the new state. - Any mutations outside of
setStatewill NOT trigger a re-render.
-
-
State is shared between components via
props.- Some
propssimply pass static data - Other
propspass functions that can pass data back out of a component. (See example below)
// When an answer is clicked, it passes its pirate property to it's parent // via the its onSelected property. // Answer.js ... <div className="card mb-3 answer" onClick={() => { if (!props.disabled) props.onSelected(props.pirate); }}> ... // GameBoard sets Answer's onSelected property to its own // handleAnswerSelected method. In this way, the parent (GameBoard) is able // to get data from it's child (Answer) // GameBoard.js ... <Answer key={p.name} pirate={p} onSelected={this.handleAnswerSelected} disabled={p.disabled} /> ...
- Some
- Add a Reset Score button to the state-api app. When clicked, the button should update the correct and incorrect counts to zero.
- Simplicity
- Little to no "magic" - no hidden logic
- Negates the need for external libraries which lead to compatibility complexity.
- Data sharing is only possible via a component Parent/Child relationship