Skip to content

Instantly share code, notes, and snippets.

@glortho
Last active April 24, 2018 11:12
Show Gist options
  • Select an option

  • Save glortho/23715563d2b74d0ae5bb to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown

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