// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
@ -88,7 +88,7 @@ MyComponent.propTypes = {
color: PropTypes.string,
fontSize: PropTypes.number
}),
// An object with warnings on extra properties
optionalObjectWithStrictShape: PropTypes.exact({
name: PropTypes.string,
@ -196,3 +196,47 @@ class Greeting extends React.Component {
```
The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. The `propTypes` typechecking happens after `defaultProps` are resolved, so typechecking will also apply to the `defaultProps`.
### Function Components
If you are using function components in your regular development, you may want to make some small changes to allow PropTypes to be proper applied.
Let's say you have a component like this:
```javascript
export default function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}
```
To add PropTypes, you may want to declare the component in a separate function before exporting, like this:
```javascript
function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}
export default HelloWorldComponent
```
Then, you can add PropTypes directly to the `HelloWorldComponent`: