PropType Utils

Introducing prop-type-utils

I recently build a react development utils package and thought I would share my reasons and how I build this package.

 

Why?

The React prop-types package provides a standard array of checks for your React component props. These include basic checks for JavaScript primitives such as Number, String, Function etc. You can even define complex objects and enum like values. As show below:

PropTypes also allows you to set if a prop is required, this will display a warning message in the browser console when this prop has not been provided. Note this only happens in development mode. This can help developers understand required props for components, its very useful when the component you are using has no or little documentation.

 

However there could be a case when you need to link props, e.g. if you have a Modal component that has a isOpen prop which is required and a name prop which only exists when the model is open. The name is required also but only really needed when the modal is open. prop-type-utils to the rescue, using the custom prop type function you can create your own PropType checks.

 

How?

PropTypes provides a custom function PropType, this allows you to write your own checks. The check function takes the component props, the prop name and the component name. As show below:

As you can see when preforming the check you can return a Error if the check fails, else return nothing. From this I decided to build out my own utils.

PropType Utils

Prop Type Utils is a collection of useful prop type validation rules.

isEven

isGreaterThan

isLessThan

isBetween

includes

isRequiredWhen

 

chrislaughlin

 

Leave a Reply

Your email address will not be published. Required fields are marked *