This lesson will teach you the basics of setting properties in your React components.
Transcript
So the purposes of this lesson, we're going to strip our main JS down to just import app from app, since we're going to be doing our rendering directly from our app.js. We can pass values into our component using something called props or properties, this is going to look a lot like passing in attribute or setting an attribute on a standard HTML element. So here I've got an attribute or a prop called text, I'm going to pass in, "This is the props text."
Now the way we access that from within our component is by interpolating this value with curly brackets, and we say this.props. whatever the name of the prop is, so in our case it's txt for text, we'll save that, on the right here we get our, "This is the props text." Now outside of JSX we don't need to interpolate that, so I'm going to set a variable here called text to this.props.text and we'll go ahead and use that in our JSX, that's just text. I'm going to go ahead and update this to value just so we can see it happen on the page.
Now we've got our, "This is the props value." We can also define the property types that we're expecting by adding a property to our component called proptypes, and that's just going to be an object where each key of the object is the name of our property, and then we pass in the type from React that we're expecting. So in this case, React.proptypes.string means we are expecting a string here. I'm going to create one more called cat, and that's going to be a React proptype of number.
When I save this, this is going to work just fine. However, on any of these proptypes we can tack on isRequired. Sorry, that should be a capital R, isRequired defines that this is a required property. So if I save this, we're going to get an error here that the required prop of cat was not specified in app. So here in our app component, I'm going to say cat = 5, save that, and now everything's working as we expected.
We can also define default properties, again by setting a property on our class component here it's going to be default.props again it's going to be an object and it follows basically the same pattern. The key is the name of our property and then the value that follows that is the default value for that prop. So I'll this is the default text here, going to save that, and on the right what you'll see is that the property that we passed in is actually overriding that, so if we save it, we should get our default property value.