mirror of
https://github.com/airbnb/javascript.git
synced 2026-04-25 03:00:19 -04:00
[guide] [react] add note that defaultProps must always be provided for non-required props
This commit is contained in:
@@ -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 doesn’t 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)
|
||||
|
||||
Reference in New Issue
Block a user