8000 add set-default-component-props.md · learnreactjs/learnreactjs@3e2e08e · GitHub
[go: up one dir, main page]

Skip to content

Commit 3e2e08e

Browse files
committed
add set-default-component-props.md
1 parent 8f8b84b commit 3e2e08e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Setting Default Component Props
2+
3+
Default props can be set when a component is being defined by using PropTypes [prop-types](https://www.npmjs.com/package/prop-types) modules or [prop-types.js](https://unpkg.com/prop-types@15.6/prop-types.js) file.
4+
5+
PropTypes defines type and which props are required. This benefits the future you using your component in two ways:
6+
7+
* You can easily open up a component and check which props are required and what type they should be.
8+
* When things get messed up React will give you an awesome error message in the console, saying which props is wrong/missing plus the render method that caused the problem.
9+
10+
## Usage
11+
12+
In the example below we define `props` type and validation:
13+
14+
```javascript
15+
class MyComponent extends React.Component {
16+
render() {
17+
// ... Do things with the props
18+
}
19+
}
20+
21+
MyComponent.propTypes = {
22+
name: PropTypes.string,
23+
age: PropTypes.number.isRequired,
24+
}
25+
26+
MyComponent.defaultProps = {
27+
name: 'Brian',
28+
age: 30
29+
}
30+
```
31+
32+
And more awesome, if we can't find a propTypes that suits our needs we can write own with regex or shapes:
33+
34+
```javascript
35+
MyComponent.propTypes = {
36+
email: function(props, propName, componentName) {
37+
if (!/emailRegex/.test(props[email])) {
38+
return new Error('Give me a real email!');
39+
}
40+
},
41+
}
42+
```
43+
44+
In the example below, the `MyComponent` component has a default value for the `name` prop.
45+
46+
<p data-height="265" data-theme-id="dark" data-slug-hash="deaJYV" data-default-tab="js,result" data-user="Bunlong" data-embed-version="2" data-pen-title="deaJYV" class="codepen">See the Pen <a href="https://codepen.io/Bunlong/pen/deaJYV/">deaJYV</a> by Bunlong (<a href="https://codepen.io/Bunlong">@Bunlong</a>) on <a href="https://codepen.io">CodePen</a>.</p>
47+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
48+
49+
Default props will be set on `this.props` if no prop is sent into the component.
50+
51+
Note:
52+
53+
* The `defaultProps` is invoked once and cached when the component is created.
54+
* The `defaultProps` is run before any instances are created.
55+
* Any objects returned by `defaultProps` will be shared across instances, not copied.

0 commit comments

Comments
 (0)
0