React Props and State
React Props and State
https://glitch.com/edit/#!/wyncode-react-sandbox
We have our array of strings containing our favorite TV shows in the Shows
component.
React Props: Step 2
const Shows = () => {
return (
<ul>
{favoriteShows.map((show, index) => (
<Show key={index} showTitle={show.name} showYear={show.year} />
))}
</ul>
);
};
We'll pass our object as properties to the Show component. We originally mapped through the
favoriteShows array directly in our Shows component. Instead, we’re going to change our map method
so that it returns a Show component for each element in that array.
Hrm, what’s up with that “index” stuff? And why am I passing the property in the parent container?
React Props: Step 3
const Show = props => {
return (
<li>
{props.showTitle} ({props.showYear})
</li>
);
};
Now we’ll need to create a new Show component for each invididual show. WHY?
HOW? WHAT’S GOING ON HERE?!
Check For Understanding
https://glitch.com/edit/#!/wyn-bunches-of-squ
ares
● Why are we setting state for color? What else could we do?
Referring to State Within Your Class Component
render() {
return(
<h1>{this.state.color}</h1>
)
}
render() {
return(
<h1>
My favorite color is{" "}
<span style={{ color:
this.state.color }}>{this.state.color}</span>
</h1>
)
}
What should I do? Use the example in the previous slide. Ask
questions. Identify specific pain points. HOOKS ARE THE
FUTURE! :D
A few notes on hooks
● What were the hooks that we used in our re-factoring of the color
changing squares?
● There are others!
● Class components and lifecycle methods are still around, but hooks are
increasingly becoming industry standard
● In class, I will mostly be writing hooks (why?)
● HW may still reference classes and event handlers -- this is a good
thing. You’ll understand Google examples and know how to set and
update state both ways.
Now You Try!
● Using React hooks:
○ Set a state for the size of the square (in pixels)
○ Update the state to a different size when the square is
clicked once
○ Revert the state back to its original size when the square
is clicked
● Update the styling in your JSX tags to reflect the state of the
square size so that it actually changes size when it’s clicked
● Reference the Glitch example for assistance
● Ask questions!
Check For Understanding
● What are React hooks?
● How do you set and update state using React
hooks?
● Compare and contrast setting and updating
state in class components, lifecycle methods,
and React hooks. Which do you like best?
Explain.
Let’s recap:
● I will be able to compare and contrast React
props and state
● I will be to set and update state in React class
components using event handlers and lifecycle
methods.
● I will be able to set and update state in
functional components using React hooks.
Week 6 Retro