1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Enforce Specific Values With PropTypes as a react til

This commit is contained in:
jbranchaud
2018-03-27 10:52:45 -05:00
parent 2d18c38fdf
commit 94a9d51045
2 changed files with 25 additions and 1 deletions

View File

@@ -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)