[guide] [react] add note that defaultProps must always be provided for non-required props

This commit is contained in:
Jordan Harband
2016-11-09 22:53:09 -08:00
parent ec08ca84ba
commit b73649925a

View File

@@ -337,6 +337,35 @@
))}
```
- Always define explicit defaultProps for all non-required props.
> Why? propTypes are a form of documentation, and providing defaultProps means the reader of your code doesnt have to assume as much. In addition, it can mean that your code can omit certain type checks.
```jsx
// bad
function SFC({ foo, bar, children }) {
return <div>{foo}{bar}{children}</div>;
}
SFC.propTypes = {
foo: PropTypes.number.isRequired,
bar: PropTypes.string,
children: PropTypes.node,
};
// good
function SFC({ foo, bar }) {
return <div>{foo}{bar}</div>;
}
SFC.propTypes = {
foo: PropTypes.number.isRequired,
bar: PropTypes.string,
};
SFC.defaultProps = {
bar: '',
children: null,
};
```
## Refs
- Always use ref callbacks. eslint: [`react/no-string-refs`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md)