React Props and State
What you will learn
● 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.
Prerequisites
● Into to React
Intro to React Practice!
● cd into your directory for this cohort
● Follow the steps outlined in the Intro to React slide deck to create a new project
called my-old-shows (you don’t need to re-install node or yarn)
● Make sure your file structure follows best practices outlined in this slide deck
● In your App.js file, you will see the parent <div className="App">
element (this is important!). Leave that.
● Erase the contents of the div (the <header> element and everything inside of
it) in App.js
● Instead, inside of your parent <div>, write a <p> tag that says hello world
● What questions do you have? What errors did you make? How did you debug
them?
● Help a friend :)
Intro to React Practice! (Part 2)
● Create a new file src/components/Shows.js
● (HUH?)
● Within Shows.js, create an array of objects called favoriteShows that
contains five of your favorite OLD SCHOOL TV shows. Each object should
have a showTitle property, and a year property that displays when
the show first premiered
● Within Shows.js, create an ARROW FUNCTION (WHY?) that will map
through an array and display each element of the array (HOW IN JSX?)
● Which kind of component is this? Why are we doing this?
● Add export default Shows; at the bottom
● Display the Shows component in your App component
There is another way!
Our code in glitch format
https://glitch.com/edit/#!/wyncode-react-sandbox
What differences do you see in how this project/these
components are structured vs how we structured
ours?
React Props
● They’re like function
arguments in JavaScript
and attributes in
HTML...what does that
mean?
● Let’s look at the example in
glitch...what are the props?
● Let’s incorporate props into
our my-old-shows project
step by step
React Props: WHY?!
App.js rendered the Shows component, which
mapped through an array and displayed
properties from each object in the array. That’s
fine I guess, but actually...are you sure? Let’s
look at Netflix as an example.
React Props: Step 1
const favoriteShows = [
{ name: 'Matlock', year: 1984 },
{ name: 'Love Boat', year: 1984 },
{ name: 'In The Heat of the Night', year: 1984 },
{ name: 'The Golden Girls', year: 1984 },
{ name: 'The Honeymooners', year: 1983 }
];
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
● How would you explain props in React?
● When and why might you use them?
● What are some rules about props that it’s
important to know?
● Can you think of any limitations of props?
The Problem(s) With Props
● One-way data is sent through components
(what does this mean?)
● Read only (what does this mean?)
The Concept of State in React
● Any piece of data within your app that can
be changed can be stored, displayed, or
updated using state
● How is this different from props?
● What’s going on in the image to the left?
What is the state that’s changing? Why is it
changing?
Let’s See What We’ll Be Building
https://glitch.com/edit/#!/wyn-bunches-of-squ
ares
How would we do this in vanilla JavaScript? Would you
enjoy that? Explain.
On the first day, God created manual DOM manipulation
Ye Olde Thyme DOM Manipulation
Then React sped things up a lot
● We’ll start by building the first kind of component created by React: a
class based component
● How will we do this? Where will we do this? Why will we do this? What
should we remember?
● As soon as we’ve created our component, we will add a line inside of
our class
● 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>
)
}
Which parts are familiar from Intro to React?
Which parts are unfamiliar? Ask questions!
Let’s jazz this up a bit with some React inline styling
render() {
return(
<h1>
My favorite color is{" "}
<span style={{ color:
this.state.color }}>{this.state.color}</span>
</h1>
)
}
Woahhhh. What’s happening here?
Next, we’ll add a square. Why’s it so ugly? What will break?
render() {
return(
<React.Fragment>
<h1>
My favorite color is{" "}
<span style={{ color: this.state.color }}>{this.state.color}</span>
</h1>
<div
id="box"
style={{ backgroundColor: this.state.color }}
onClick={this.changeColor}
>
Click Me
</div>
</React.Fragment>
)
}
Let’s make our square do stuff when we click on it!
changeColor = () => {
let colors = [
"red",
"orange",
"yellow",
"green",
"blue",
"indigo",
"violet"
];
colors = colors.filter(color => color !== this.state.color);
const randomIndex = Math.floor(Math.random() * colors.length);
const randomColor = colors[randomIndex];
this.setState({ color: randomColor });
};
Now You Try
● Navigate out of wyn-squares and back
into your wyncode directory
● Create a new React project, wyn-message
● Following a similar pattern to how we
just set and updated state, set a state for
a message inside of the square
● When a user clicks the square, the click
should trigger an event handler, which
should change the message inside the
square to one of 10 of your favorite movie
quotes (don’t worry about changing the
color anymore, unless you want to)
Check For Understanding
● How do you set and update state in a class
component in React?
● What order did we write our code in?
● Do you like this? Why or why not?
Setting and Updating State With Lifecycle
Methods in React
● Check out the SquareLifecycle.js file in our src
directory in Glitch.
● What do you notice that’s different?
● Is state being updated? How might we do that? Let’s try!
● Let’s check out our console to see when our
componentWillMount, componentWillUnmount,
and componentDidUpdate methods are getting invoked
● Common use cases: API calls (why? How? OH GOD APIs
AGAIN)
● Examples/other use cases (Ernie, Leo, Laz)
Now You Try
● Modify the three React lifecycle methods we’ve discussed
so that SOMETHING DIFFERENT happens upon the trigger of
componentWillMount, componentDidUpdate, and
componentWillUnmount
● This could be as simple as a different console.log
message or as complicated as an API call
● Ask questions!
Check For Understanding
● What are React
lifecycle methods?
● How can you use
lifecycle methods to
set and update state?
● Do you like this way?
Why or why not?
Now Introducing React Hooks!
Just kidding actually hooks are awesome.
Advantages of Hooks
● Set and modify state without writing a class based component (why is this
preferable? :-O // are we abandoning OOP???)
● It’s cleaner. Look at the example & explain & ask questions.
● What’s different? What’s the same? What are your pain points looking at this
code?
Let’s Refactor Our Color Changing Squares in Hooks!
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
Please complete our week 6 retro:
● https://www.goreflect.com/Retrospective/Boar
d/FfYaaV1BW0O0-mU9Lx3WQw