Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Define Prop Types for a React Class Component

    Andy Van SlaarsAndy Van Slaars
    reactReact
    ^16.6.1

    React components rely on props for any data that isn’t encapsulated into their internal state. We can help ensure that our components receive their required props and that the props passed in are of the correct types by defining prop types for our components. In this lesson, we’ll see how the React ESLint plugin enforces the use of prop types and how to define them in a component using the prop-types package.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Looking at this error boundary component, we can see that it relies on a prop called Children. If we run our linter with MPM run lint, we'll see that it fails. I'm going to expand this, and we'll see that it's failing because we're not explicitly calling out this prop requirement.

    00:19 We need to specify this with React prop types. I'll go back into my code. At the top of this file, I'm going to do an import prop types from prop types. Then down in my component, I'm going to add a static property called Prop Types. This is going to equal an object.

    00:46 That object is going to map to properties that we expect, their data type, and if they're required or not. In this case, we only have one. We're going to define a key called Children. The value for this is going to be proptypes.node, because we expect a React node to be passed in as the Children for this error boundary.

    01:05 Then, we're going to specify that that is required. We can save that. Then back in our terminal, I can MPM run lint. This time, we'll see that it passes.

    Discuss

    Discuss