react-schema
Use react PropTypes for generic object validation.
Concept
React provides an extraordinarily concise yet powerful way of defining component API's via PropTypes. This module:
- Makes it easy to re-use that system for generic validation of object structures decoupled from React UI components.
- Provides an introspectable version of the PropTypes.
Getting Started
npm install react-schema
Validation
Validate an object against an API definition:
;; // An API schema.const mySchema = isEnabled: ReactPropTypesboolisRequired width: PropTypesnumberOrString; const myData = isEnabled: true width: "10px"; // Validate an object against the API.schema; // returns: { isValid: true }
Introspection
You can introspect details about each type:
; const myObject = PropTypesshape isEnabled: PropTypesbool ;myObject$metatype; // Equals: "shape"myObject$metaargs; // Equals: { isEnabled: PropTypes.bool } const myEnum = PropTypes;myEnum$metatype; // Equals: "oneOf"myEnum$metaargs; // Equals: ['one', 'two']
Defining your own custom PropTypes
If you need the introspection behavior on a custom type, you need to wrap it using createIntrospectableChecker
:
const PropTypes = ;const createIntrospectableChecker = ;const MyCustomPropType = { // ...}; // First, we create an introspectable instance of it:const MyIntrospectableCustomPropType = ; // Now, we register it as a PropType:PropTypesMyCustomPropType = MyIntrospectableCustomPropType;
Here's how to register an analyzer for a certain propType:
const PropTypeAnalyzer = ; // @args will be whatever the propType checker was instantiated withPropTypeAnalyzer; // Later on in your consumer code:const schema = someProp: PropTypes; console;// => { type: 'whatever', fields: [{ type: 'literal', value: 'foo' }]}
And here's how to register a custom formatter:
const PropTypeFormatter = ; // @args will be whatever the propType checker was instantiated withPropTypeFormatter; // Later on in your consumer code:const schema = PropTypes; console;// => "MyCustomProp: [foo]"
toString
Property definitions created from the module wrapper provides expressive details about each type when converted to a string.
You can cast a PropType node to a descriptive string (provided it has a formatter defined) using the PropTypeFormatter
:
;; const myEnum = PropTypes;; // => "oneOf(one, two)"
Additional Types
The complement the base PropTypes, the following commonly used definitions are available:
PropType.numberOrString
PropType.boolOrString
Test
# Run tests.
npm test
# Watch and re-run tests.
npm run tdd