Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
This video covers one solution to the *Provider and Consumer Challenge*.
Resources
In the previous video, I challenged you to
modify the player list component to use
0:00
a consumer that has access to
the context set by the provider and
0:04
returns to the list of players.
0:08
Now I'll show you my solution.
0:10
I'll start by importing consumer
at the top of PlayerList.js
0:12
with import { Consumer } from './Context'.
0:17
Next, I'll add the consumer component
inside the return statement.
0:22
Remember, consumer
requires a render prop or
0:29
a function as a child that returns
the part of the UI you want to render.
0:32
So I'll open a JSX expression
with a set of curly braces,
0:37
then write a function that
takes the parameter context.
0:41
This time, I'll use an implicit return,
which means that
0:46
I'll omit the return keyword and
wrap the JSX within parenthesis.
0:48
Now I'll move the entire fragment
containing the map function inside
0:53
the parentheses, and access
the player's data directly from context
0:58
by replacing props.players with context.
1:04
The app displays the list
of players in the same way,
1:10
except that it's no longer
coming in through props.
1:14
So now, I can remove the players
property and the propTypes.object,
1:16
and delete the players prop passed to
the player list component in app.js.
1:23
And that should do it.
1:30
If you're wondering about the object
spread attribute passed to the player
1:31
component, I'm using it to pass the name,
score and ID properties we're getting from
1:35
each player object via
map all at once as props.
1:40
That way you don't have to explicitly
list each prop name and value.
1:44
Using the spread operator, you're still
able to access each prop by its name
1:48
in the player component with
this.props.name, this.props.id, and
1:53
this.props.score, for example.
1:58
Most of the app is now accessing
the player's data from context.
2:00
However, there's still a bit
of prop drilling going on
2:05
to distribute the event handlers
written in the app component.
2:08
So in the next video, we'll pass
each function to the provider, so
2:12
that we're able to access and
invoke them from inside a consumer.
2:16
You need to sign up for Treehouse in order to download course files.
Sign up