React ~ Component API - rohit120582sharma/Documentation GitHub Wiki
Default values can be assigned to the props using defaultProps. When a component does not receive it’s props, then it resorts to the defaultProps that has been assigned.
MyComponent.defaultProps = {
text: 'Sample Deafult Text',
content: [],
onPress: () => {},
size: 0,
styles: {},
isReady: false
}
PropTypes ensure that the right type of props is passed to a component — and, conversely, that the receiving component is receiving the right type of props.
We can use the propType for validating any data we are receiving from props.
Just like defaulProps, propTypes are also objects where keys are the prop names and values are their types.
By default the props for a component are optional. By adding the isRequired keyword, we are making sure a warning is generated if the prop is not provided to the component.
import PropTypes from 'prop-types';
MyComponent.propTypes = {
// By default, all are optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// A React element
optionalElement: PropTypes.element,
// A value of any data type
optionalAny: PropTypes.any,
// You can chain any of the above with `isRequired` to make sure a warning is shown if the prop isn't provided.
requiredAny: PropTypes.any.isRequired,
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
}),
// An object with warnings on extra properties
optionalObjectWithStrictShape: PropTypes.exact({
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
}),
}