Autoplay

    Set Properties on React Components

    Joe MaddaloneJoe Maddalone

    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.

    reactReact
    0.14 - 16
    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

    00:00 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."

    00:18 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.

    00:48 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.

    01:05 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.

    01:29 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.

    01:45 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.

    02:03 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.

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

    Discuss

    Discuss