Become a member
to unlock all features

Level Up!

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


    Set Properties on React Components

    0.14 - 16

    This lesson will teach you the basics of setting properties (props) in your React components. As stated in Thinking in React, props are how we pass data around in React. We will take a look at what propTypes and defaultProps do for us in React.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    We can pass data into our components by using what's called props. Here, I've created a prop called text. This looks a lot like passing an attribute into an html element. I'm going to set that to a string of, "This is the prop text."

    In our component, we can access our props by interpolating with curly brackets, this.props, and then, the name of the prop that we're looking for. In our case, it's txt. Save that and we can see, "This is the prop text." Now, outside of JSX, we don't need to interpolate that, so, I can say, let text equal is props.txt, and then in our JSX, I can just use that variable name txt.

    Just so we can see that change in the browser, I'm going to update our value to, "This is the prop value," and we can see that there in our browser. Now, we can define the properties that we're going to be looking for in our component by adding a property to our component called PropTypes.

    This is going to be an object where each key is the name of the property, and each key's value is the type of value that we're looking for. If we're text, I can say I'm looking for react.PropTypes.string. I'm going to create one more here which can be called cat. I'm going to say react.PropTypes.number is what we're looking for. In this case, we're looking for a number. I can save that. Everything's going to work just fine.

    However, on each of these PropTypes, we can add an isRequired to it. When I save that, everything's going to work fine, but we can see here in the console that the prop cat is marked as required in app, but its value is undefined.

    If I jump back over to our component usage, and say, cat equals, we'll set that to five, everything's working again. We're not getting that error. We can also set a series of default properties by adding a property to our component called defaultProps.

    Again, this is going to be an object where each key is the property. I'm going to set our default for text to, "This is the default text." I'm going to save that. What we're going to see is that the value that was passed into our component actually overwrites the default.

    Once I clear that out, we get our, "This is the default text," which is the default property that we set for our component.