Skip to content

Instantly share code, notes, and snippets.

@glortho
Last active April 24, 2018 11:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glortho/23715563d2b74d0ae5bb to your computer and use it in GitHub Desktop.
Save glortho/23715563d2b74d0ae5bb to your computer and use it in GitHub Desktop.
Nullable PropType for React
/**
* Usage:
*
* import React from 'react';
* import nullable from 'prop_nullable';
*
* let myClass = React.createClass({
* propTypes: {
* myProp: nullable( React.PropTypes.string ).isRequired,
* myOtherProp: nullable( [React.PropTypes.string, React.PropTypes.number] )
* }
* });
*/
import { PropTypes } from 'react';
let { oneOf, oneOfType } = PropTypes;
export default types => oneOfType( [ oneOf( [ null ] ), ...[].concat( types ) ] );
@AoDev
Copy link

AoDev commented Aug 27, 2015

Nice, I hope something like this is integrated in React. Although I like the Joi way for validations more.
https://github.com/hapijs/joi

You can do something like this:

Joi.string().allow(null).required();

A "white list" like allow(whatever) is more flexible.

@lakesare
Copy link

This doesn't raise any warning if types is undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment