Props are the mechanism React uses to let components communicate with each other. A parent component can pass it’s child(ren) named prop values, which the child can then use in its internal logic. It looks something like this:
As you can see, the ParentComponent passes the string “Narwhal” and number 3 to the properties ‘message’ and ‘id’ of ChildComponent. React components have an internal property ‘props’. This property contains all the props a component gets from its parent. So in this case ChildComponent would get the message via this.props.message, everything great so far!
Imagine you are working in a bigger project with many, more complex components. Say a fellow developer is going to build a feature and he needs to use ChildComponent, how is he going to know ChildComponent needs a property message and id to function properly? Yes, he will need too search the components code for usages of the this.props object. He will also need to figure out what type those properties need to be. In more complex components this can be a time consuming activity.
This is where Reacts propTypes come in. It’s essentially a dictionary where you define what props your component needs and what type(s) they should be. How doesthis look like?
ChildComponent does exactly the same as before, however, your fellow developer will know by reading the propTypes that he needs to pass in a property called message of type string. The isRequired property tells you beloved colleagues that the property is required for the component to work. Here are a few more possibilities:
So what happens if you do not conform to the defined propTypes? Well if you provide a prop of the wrong type or don’t provide a required prop, React will log a warning to the console at runtime. React will only do this when you are in a development environment (defined by the global NODE_ENV variable) to save performance in production.
You can use envify to set the NODE_ENV variable. It is a global environment variable used by a lot of nodejs applications. You could have a seperate dev and production gulp task. In the production build you would set NODE_ENV to ‘production’. For more information: npmjs.com/package/envify.
The propTypes object kind of defines the ‘interface’ for using a component. Always put it near the top of your component. Define a prop in the propTypes before you write any code using the actual prop. This prevents you from forgetting and makes you more aware of the ‘dependencies’ your component has to external data.
I think ‘propTypes’ is one of the strongest features of React. It also shows that the developers of React care and they want it to be a professional framework. Although propTypes are optional, you should always use them!
- React PropTypes: facebook.github.io/react/docs/reusable-components.html
- Envify: npmjs.com/package/envify