Prop-types is a library that allows to introduce some validation on the props we pass to React components.
It works only in development mode , writing warning/errors in the console when a prop passed to a component is not valid, allowing us to discover this kind of issues before it's too late.
Some validators are already provided, but the library permits to create your own custom validator as well. That's what I did it today.
In my case I needed a simple validator for String props, which would return me an error when a not valid or empty string is passed to a component.
After having installed the library
npm install --save prop-types
I implemented the custom validator in an external js file
// /utility/validators.js
const propStringValidator = (props, propName, componentName) => {
const prop = props[propName];
if (prop && typeof prop === "string") {
return;
}
return new Error(
`${componentName} -> Invalid prop ${propName} : not a valid or empty string`
);
};
export {propStringValidator}
As for the parameters needed by the custom validator, I followed the same convention shown in the official doc example, that is
- props: the array containing all the props of the component
- propName: the name of the current prop to validate
- componentName : the name of the component
Then I used the validator in my component pretty much like this
// MyComponent.jsx
import PropTypes from "prop-types";
import { propStringValidator } from "/utility/myValidators";
export default function MyComponent ({
componentDescription
}) {
MyComponent.propTypes = {
componentDescription: propStringValidator,
};
I didn't set explicitly the values fpr "propStringValidator" parameters Their values are automatically filled by the library itself.
So now, in case the "componentDescription" prop passed to "MyComponent" is:
- null
- undefined
- empty string
- something which is not a string
this error is now notified in the console like this
Warning: Failed prop type: MyComponent -> Invalid prop componentDescription : not a valid or empty string
Did I write anything wrong ? Or you have better ideas? Please share it in the comments :-)