Search code examples
javascriptreactjsreusabilitycode-reusereact-proptypes

How to make reusable proptype validations?


Assume that I have a parent component called Logo which contains two child components respectively Image and Text. Below code shows how I validate the parent component's props.

Logo.propTypes = {
  type: PropTypes.string,
  children: PropTypes.oneOfType([
    PropTypes.shape({
      type: PropTypes.oneOf([Image, Text])
    }),
    PropTypes.arrayOf(
      PropTypes.shape({
        type: PropTypes.oneOf([Image, Text])
      })
    )
  ])
};

This is working fine and does what I really want.
But I have so many other components which I do the same children validation nut only the change is PropTypes.oneOf([Image, Text]) array. So, in that case, I think there should be a common way of using this in javascript/react making this code snippet reusable across the components.


Solution

  • You could think in a fancier solution, but propTypes is really just an object, what if you turn it into a function which receives two parameters image and text and return an object, so you could just import it in your components:

    export const myPropTypesCreator = (image, text) =>({/*return the object*/})
    

    And inside your components:

    import { myPropTypesCreator } from './mypath'
    Logo.propTypes = myPropTypesCreator(image,text)