⚠️ This lesson is retired and might contain outdated information.

Use propTypes in Reusable React Native Components

Tyler McGinnis
InstructorTyler McGinnis
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 2 years ago

In this React Native lesson, we will be creating a reusable Badge component. The component will also make use of propTypes to validate that its required data is being passed in when it is used.

[00:00] We're going to make this a component and then reuse that component in the profile component, the repositories component, and the notes component we're going to build. In our components folder, let's go ahead and create a new file called Badge.js. We're going to require React. We're going to disjuncture our object and get some stuff it needs.

[00:23] We'll need some text, view, the image, and a StyleSheet, so that equal to React. I'm going to paste it in the styles.

[00:33] Now what we're going to do is let's go ahead and make our Badge class which extends React component. As always, module.exports=Badge. This Badge is going to be in React. There are these things called pure components. It's components that don't have a state but they will take in their data from their parent component.

[00:57] When we render Badge, we're going to have to make sure that we pass the appropriate data. Some things we can do later on to make sure that we do that. If we don't do that, it will throw a warning.

[01:06] What we're going to do here is return our UI. Let's have a view with some styling on it. Then, we're going have an image component with some styling on it as well. The source is going to be, we're going to use URX to URL. It's going to be on the userInfo object that we pass in when we use our Badge component.

[01:34] We're also going to have some text here. Let's have the name attribute as a property. The text is going to be userInfo.name. We're going to have some more text whose value is going to be this.props.userInfo.login.

[01:49] Now that we have this component, you'll notice here that this component is very much reliant on this userInfo object. If we don't pass this userInfo object in, this entire component is going to break. What React gives us is this thing called propTypes. We can get the name of the class, add propTypes on to it. What this will do is this will verify that certain properties are there, certain properties of certain type. It's super useful.

[02:22] If when we invoke our Badge class or when we use our Badge component, if we don't pass in userInfo object, it's going to throw an error in the console. We're going to see our prop types. We need to have some user info and it's going to be an object and it is required. In order for this component to run and not throw an error, we need to have this userInfo object passed in when we use our Badge component.