1
1
# Prevent missing props validation in a React component definition (react/prop-types)
2
2
3
- PropTypes improve the reusability of your component by validating the received data.
3
+ Defining types for component props improves reusability of your components by
4
+ validating received data. It can warn other developers if they make a mistake while reusing the component with improper data type.
4
5
5
- It can warn other developers if they make a mistake while reusing the component with improper data type.
6
+ You can provide types either in runtime types using [ PropTypes] or statically
7
+ using [ TypeScript] or [ Flow] . This rule will validate your prop types regardless
8
+ of how you're defining them.
6
9
7
10
## Rule Details
8
11
@@ -36,6 +39,18 @@ Hello.propTypes = {
36
39
}
37
40
```
38
41
42
+ In TypeScript:
43
+
44
+ ``` tsx
45
+ interface Props = {
46
+ age: number
47
+ }
48
+ function Hello({ name }: Props ) {
49
+ return <div >Hello { name } </div >;
50
+ // 'name' type is missing in props validation
51
+ }
52
+ ```
53
+
39
54
Examples of correct usage without warnings:
40
55
41
56
``` jsx
@@ -76,6 +91,19 @@ class HelloEs6WithPublicClassField extends React.Component {
76
91
}
77
92
```
78
93
94
+ In Flow:
95
+
96
+ ``` tsx
97
+ type Props = {
98
+ name: string
99
+ }
100
+ class Hello extends React .Component <Props > {
101
+ render() {
102
+ return <div >Hello { this .props .name } </div >;
103
+ }
104
+ }
105
+ ```
106
+
79
107
The following patterns are ** not** considered warnings:
80
108
81
109
``` jsx
@@ -115,11 +143,11 @@ As it aptly noticed in
115
143
116
144
> Why should children be an exception?
117
145
> Most components don't need ` this.props.children ` , so that makes it extra important
118
- to document ` children ` in the propTypes .
146
+ to document ` children ` in the prop types .
119
147
120
- Generally, you should use ` PropTypes.node ` for ` children ` . It accepts
121
- anything that can be rendered: numbers, strings, elements or an array containing
122
- these types.
148
+ Generally, you should use ` PropTypes.node ` or static type ` React.Node ` for
149
+ ` children ` . It accepts anything that can be rendered: numbers, strings, elements
150
+ or an array containing these types.
123
151
124
152
Since 2.0.0 children is no longer ignored for props validation.
125
153
@@ -132,3 +160,7 @@ For now we should detect components created with:
132
160
* a function that return JSX or the result of a ` React.createElement ` call.
133
161
* ` createReactClass() `
134
162
* an ES6 class that inherit from ` React.Component ` or ` Component `
163
+
164
+ [ PropTypes ] : https://reactjs.org/docs/typechecking-with-proptypes.html
165
+ [ TypeScript ] : http://www.typescriptlang.org/
166
+ [ Flow ] : https://flow.org/
0 commit comments