Getting Started with React: Lesson 13 of 14


Up Next


Autoplaying in 7 seconds!


When creating a component for reuse, it can be helpful to be able to document and enforce the props and their types that a component expects to receive. Luckily, React gives us a built-in way to do this. It exposes all the prop types it can enforce on React.PropTypes. We can then enforce them by setting an object on the class object called propTypes. Let's see this in action on the ZipForm component. Add the following to the bottom to the ZipForm.js file.

ZipForm.propTypes = {
  zips: React.PropTypes.arrayOf(React.PropTypes.number).isRequired,
  onSubmit: React.PropTypes.func

Here we are setting propTypes on the ZipForm. There is a zips key. We designate that it is an array of numbers and is required. We are also saying that we accept an onSubmit prop that is a function but it is not required. This could cause some issues in our code when we try to call onSubmit but it is undefined. Everything will break! We could make a default in the class itself, but there is a better way. We can setup default props on the class object itself to keep our code nice and clean. Add this below the prop types.

ZipForm.defaultProps = {
  onSubmit: () => {}

Here we are setting an empty function to be the onSubmit prop. This way when it is called, nothing happens but the code doesn't explode. Sweet!

Table of Contents

    We can do this same thing to all our components! It helps make sure it is easy to use our components in the future, whether it is us using them or other people.

    Alex Sears

    2 posts

    Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?