propTypes
and defaultProps
The great thing about React component is that they let you make reusable chunks of functionality, and share them with other people. But components can get pretty large, and it isn’t always obvious which props you’ll need to supply.
Luckily, React provides a few tools to help.
propTypes
Each React component can have a special propTypes
property that specifies the type of props
that it expects to receive.
React will log a warning if you try and create an element with incorrect types.
Simple, huh? But where did that PropTypes
object come from?
Actually, PropTypes
is imported from a separate package, called prop-types
. The above editor’s build system is smart enough to download it automatically, but if you’re using Create React App then you’ll need to install it.
The PropTypes
object provides a number of different validators. The example above uses the PropTypes.string.isRequired
and PropTypes.string
validators, but you can also check for numbers, elements, arrays, and many other types. A full list is available in the official documentation. Or if you want something more compact, you can print out my React Cheatsheet.
defaultProps
React components can also have a special defaultProps
property. When you assign an object to defaultProps
, React will merge that object with the props provided to createElement()
when needed. This comes in handy when you want to provide sensible defaults.
For example, you could use defaultProps
to ensure that a bootstrap-based Button
component applies the default
when no other color is specified.
To get a feel for this, try removing the defaultProps
from the below example and watching how the console and rendered button changes.