From 94a9d5104500ebe03ffbebfe620928569cdc05b3 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 27 Mar 2018 10:52:45 -0500 Subject: [PATCH] Add Enforce Specific Values With PropTypes as a react til --- README.md | 3 ++- .../enforce-specific-values-with-proptypes.md | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 react/enforce-specific-values-with-proptypes.md diff --git a/README.md b/README.md index 78b9f36..8f8dd84 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_650 TILs and counting..._ +_651 TILs and counting..._ --- @@ -451,6 +451,7 @@ _650 TILs and counting..._ - [Destructure Variables As Props To A Component](react/destructure-variables-as-props-to-a-component.md) - [Dispatch Anywhere With Redux](react/dispatch-anywhere-with-redux.md) - [Dynamically Add Props To A Child Component](react/dynamically-add-props-to-a-child-component.md) +- [Enforce Specific Values With PropTypes](react/enforce-specific-values-with-proptypes.md) - [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md) - [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md) - [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md) diff --git a/react/enforce-specific-values-with-proptypes.md b/react/enforce-specific-values-with-proptypes.md new file mode 100644 index 0000000..83972db --- /dev/null +++ b/react/enforce-specific-values-with-proptypes.md @@ -0,0 +1,23 @@ +# Enforce Specific Values With PropTypes + +Being able to constrain our user interfaces to very specific values is +valuable. This makes our interfaces easier to reason about and easier to +test. PropTypes in general are one of the ways that we constrain our UIs. We +can go even further than simple type constraints by limiting a prop to a +specific set of values, an enum if you will. + +```javascript +MyComponent.propTypes = { + flavors: PropTypes.oneOf(['Vanilla', 'Chocolate', 'Strawberry']), +}; +``` + +The docs say about `oneOf()`: + +> You can ensure that your prop is limited to specific values by treating it +> as an enum. + +If we use `MyComponent` with a value such as `Pistachio`, we'll have a +console warning to answer for. + +[source](https://reactjs.org/docs/typechecking-with-proptypes.html)