Skip to content

Commit b736499

Browse files
committed
[guide] [react] add note that defaultProps must always be provided for non-required props
1 parent ec08ca8 commit b736499

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

react/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,35 @@
337337
))}
338338
```
339339

340+
- Always define explicit defaultProps for all non-required props.
341+
342+
> 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.
343+
344+
```jsx
345+
// bad
346+
function SFC({ foo, bar, children }) {
347+
return <div>{foo}{bar}{children}</div>;
348+
}
349+
SFC.propTypes = {
350+
foo: PropTypes.number.isRequired,
351+
bar: PropTypes.string,
352+
children: PropTypes.node,
353+
};
354+
355+
// good
356+
function SFC({ foo, bar }) {
357+
return <div>{foo}{bar}</div>;
358+
}
359+
SFC.propTypes = {
360+
foo: PropTypes.number.isRequired,
361+
bar: PropTypes.string,
362+
};
363+
SFC.defaultProps = {
364+
bar: '',
365+
children: null,
366+
};
367+
```
368+
340369
## Refs
341370

342371
- Always use ref callbacks. eslint: [`react/no-string-refs`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md)

0 commit comments

Comments
 (0)