Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed React Components!
You have completed React Components!
Preview
You can even use PropTypes to mark a prop as required or provide a default value if the prop isnβt provided.
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
How did it go?
0:00
If you are still needing help,
rewatch the last video and
0:00
take a look at the teacher's notes for
helpful resources.
0:04
So not only does PropTypes
validate the prop, but
0:08
you can also even make a prop required.
0:13
This can be extremely helpful
if you omit a prop altogether.
0:16
For example, if I delete the name and
0:21
score props pass the player,
our name and scores are blank.
0:24
And React doesn't warn us because the
missing props are not marked as required.
0:29
So to make sure that a warning is
shown if the prop isn't provided,
0:36
chain isRequired to your PropTypes.
0:40
Now, in the console, we get
the message warning, Failed prop type:
0:43
The prop name is marked as required in
Player, but its value is undefined.
0:48
And we get the same warning for
the score prop.
0:54
Finally, you can define default values for
0:58
your props with the default
props property.
1:01
In the file Header.js,
let's create a new object below
1:05
the PropTypes.object with
Header.defaultProps and
1:10
set it equal to an object.
1:16
Inside the defaultProps object,
1:18
we'll give the title prop
a default value of Scoreboard.
1:20
defaultProps will make sure
that title will have the value
1:25
scoreboard if it's not specified
by the parent app component.
1:29
It also gets type checked
in Header.propTypes.
1:35
Now, if we do supply the Header
a title prop via the Header tag,
1:40
the value will be used instead
of the default prop, and
1:46
also type checked in Header.propTypes.
1:50
So now, we can omit the title prop in
1:54
the Header tag because we're
defaulting it to Scoreboard.
1:57
As you've learned,
prop types not only help you catch and
2:02
avoid bugs, they also serve as
documentation for components.
2:06
Other developers working on
the same project will know exactly
2:10
which props your component takes and
what types they should be.
2:15
I'll stop here, but
why don't you go ahead and
2:20
add isRequired and default values for
the remaining components?
2:23
You can see my solution when you download
the project files for this course.
2:27
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up