27
28InputTextBox.defaultProps = {
29 inputValue: '',
30 placeholder: 'Please enter text',31};
32
33export default InputTextBox;
26};
27
28InputTextBox.defaultProps = {
29 inputValue: '',30 placeholder: 'Please enter text',
31};
32
24};
25
26CheckBox.defaultProps = {
27 inputValue: '',28 checkboxIndex: 0
29};
30
25
26CheckBox.defaultProps = {
27 inputValue: '',
28 checkboxIndex: 029};
30
31export default CheckBox;
All non-required properties in the propTypes
of a React component must declare a default value in defaultProps
.
Defining defaultProps
ensures that this.props.propertyName
will have a value if not specified by the parent component.
propTypes
is type-checked after the contents of defaultProps
is resolved, so type checking will also apply to the values defined in defaultProps
.
Why should I use defaultProps
?
- defaultProps
gives us a unified way of setting default values for props in both class components and functional components.
- Its syntax is simple and straightforward.
What could the usage of defaultProps
prevent?
- Errors that may occur while refactoring code (e.g. partially updated prop types)
- Accidentally missing component prop types
- Forgetting to set required property values for components
Bad Practice
// Example 1
function MyStatelessComponent({ property_first, property_second }) {
return <div>{property_first}{property_second}</div>;
}
MyStatelessComponent.propTypes = {
property_first: React.PropTypes.string.isRequired,
property_second: React.PropTypes.string
};
MyStatelessComponent.defaultProps = {
property_first: "property_first"
};
// Example 2
var Greeting = React.createClass({
render: function() {
return <div>Hello {this.props.property_first} {this.props.property_second}</div>;
},
propTypes: {
property_first: React.PropTypes.string,
property_second: React.PropTypes.string
},
getDefaultProps: function() {
return {
baz: "baz"
};
}
});
Recommended
// Example 1
function MyStatelessComponent({ property_first, property_second }) {
return <div>{property_first}{property_second}</div>;
}
MyStatelessComponent.propTypes = {
property_first: React.PropTypes.string,
property_second: React.PropTypes.string.isRequired
};
// Example 2
type Props = {
property_first: string,
property_second?: string
};
function MyStatelessComponent(props: Props) {
return <div>Hello {props.property_first} {props.property_second}</div>;
}
MyStatelessComponent.defaultProps = {
property_second: 'some default'
};