Props & PropTypes
1. Props
"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." Ref[2]
"React components have an internal property ‘props’. This property contains all the props
a component gets from its parent. " Ref[2]
2. PropTypes
2.1 Introduction
"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." Ref[2]
propTypes: {
//Id can be a number, or a string, but it needs to be defined!
id: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string
]).isRequired, //Messages should be an object with a title and text property of type string
message: React.PropTypes.shape({
title: React.PropTypes.string,
text: React.PropTypes.string
}).isRequired, //The comments property needs to be an array of objects.
comments: React.PropTypes.arrayOf(React.PropTypes.object), //The date needs to be an instance of type Date.
date: React.PropTypes.instanceOf(Date)
}
2.2 React.PropTypes.shape()
react@15.1.0
A): React.js
var ReactPropTypes = require('./ReactPropTypes'); // ...... var React = {
// ......
PropTypes: ReactPropTypes,
// .......
}; module.exports = React;
B): ReactPropTypes.js
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
}; // ......
module.exports = ReactPropTypes;
C): Comment for createShapeTypeChecker function
function createShapeTypeChecker(shapeTypes)
function createChainableTypeChecker(validate)
2.3 Use Case of React.PropTypes.shape()
https://github.com/reactjs/react-redux/blob/master/src/utils/storeShape.js
https://github.com/reactjs/react-redux/blob/master/src/components/Provider.js
Reference
1. Prop Validation
https://facebook.github.io/react/docs/reusable-components.html
2. Why React PropTypes are important
http://wecodetheweb.com/2015/06/02/why-react-proptypes-are-important/