Guest User

Untitled

a guest
Apr 25th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. // Example on how to go about using a prop type validator inside a custom validator function.
  2.  
  3. // In this case, we want to check of the given prop is either a string, a number, a bool,
  4. // or an instance of Moment. However, it's recommended by the package authors to use
  5. // the `.isMoment` function instead of directly checking with `instanceof`
  6.  
  7. import React from 'react'
  8. import { oneOfType, string, number, bool } from 'prop-types'
  9.  
  10. import moment from 'moment'
  11.  
  12. ExampleComponent.propTypes = {
  13. initialValue: function(props, propName, componentName, ...rest) {
  14. const propTypeError = oneOfType([string, number, bool])(
  15. props,
  16. propName,
  17. componentName,
  18. ...rest
  19. )
  20.  
  21. if (propTypeError) {
  22. const propIsInstanceOfMoment =
  23. props[propName] && moment.isMoment(props[propName])
  24. if (propIsInstanceOfMoment) {
  25. return null
  26. }
  27.  
  28. propTypeError.message += ` Should be of type '${String.name}', '${
  29. Number.name
  30. }', '${Boolean.name}' or 'Moment'.`
  31. throw propTypeError
  32. }
  33. },
  34. }
  35.  
  36. export default function ExampleComponent({ initialValue }) {
  37. return <h1>Example component</h1>
  38. }
Add Comment
Please, Sign In to add comment