From 446ba517d7fd7bc545254defe4da02268bb05ded Mon Sep 17 00:00:00 2001 From: Renato Alves Date: Wed, 25 Nov 2020 06:20:47 -0300 Subject: [PATCH] Add PropType instructions for function components (#3403) Co-authored-by: Sebastian Silbermann --- content/docs/typechecking-with-proptypes.md | 48 ++++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index e8a6a318..1eabf394 100644 --- a/content/docs/typechecking-with-proptypes.md +++ b/content/docs/typechecking-with-proptypes.md @@ -61,7 +61,7 @@ MyComponent.propTypes = { // A React element type (ie. MyComponent). optionalElementType: PropTypes.elementType, - + // 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 ( +
Hello, {name}
+ ) +} +``` + +To add PropTypes, you may want to declare the component in a separate function before exporting, like this: + +```javascript +function HelloWorldComponent({ name }) { + return ( +
Hello, {name}
+ ) +} + +export default HelloWorldComponent +``` + +Then, you can add PropTypes directly to the `HelloWorldComponent`: + +```javascript +import PropTypes from 'prop-types' + +function HelloWorldComponent({ name }) { + return ( +
Hello, {name}
+ ) +} + +HelloWorldComponent.propTypes = { + name: PropTypes.string +} + +export default HelloWorldComponent +```