Search code examples
reactjsreact-proptypes

How to use PropType inbuilt functions inside a custom validator?


I was having this validator(array of specific shape) for defaultValue prop:

defaultValue: PropTypes.arrayOf(PropTypes.shape({
        key: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
        value: PropTypes.string.isRequired
    }))

but, now defaultValue can be of string type as well. So I am trying a custom validator :

defaultValue: function (props, propName, componentName) {
  if (typeof props[propName] === "string"){

  } else if (props[propName] instanceof Array){
      //how to add old functionality here?
  } else {
      return new Error(
        `Invalid prop ${propName} supplied to ${componentName}. Validation failed`
      )
  }

}

Can I use the old PropTypes.arrayOf(....) inside the custom validator? I want to add the old validation into the new custom validator function. If using PropTypes is not possible, how to achieve the same using custom code?


Solution

  • if you just want to make default value either a string, or your custom type, you can use oneOfType with string, and your type and it would work.

    PropTypes.oneOfType([
          PropTypes.string,
          PropTypes.arrayOf(PropTypes.shape({
                    key: PropTypes.oneOfType([PropTypes.string, 
                                              PropTypes.number]).isRequired,
                    value: PropTypes.string.isRequired}))
    ])