tnrich
tnrich

Reputation: 8580

Use react proptypes for validation in purely functional code

I really like the idea of react proptypes and am wondering if they can be used to validate the input of any given function, not just the props being passed to a react component.

For example:

function doSomething (thing1, thing2) {
    Proptypes.validate(arguments, [Proptypes.string, Proptypes.number]);
}

Is there a way of getting proptypes to do this?

Thanks!

Upvotes: 2

Views: 999

Answers (2)

Chris Martin
Chris Martin

Reputation: 30736

Prop validators are functions, so you can just call them. As the customProp example in the Prop Validation doc illustrates, the arguments are props, propName, and componentName. The function returns null on success or an Error on failure. For example:

React.PropTypes.number({'a': 4}, 'a', 'foo')
// null

React.PropTypes.number({'a': 'b'}, 'a', 'foo')
// Error: Invalid undefined `a` of type `string`
// supplied to `foo`, expected `number`

Upvotes: 1

Mike Driver
Mike Driver

Reputation: 8511

Yes they can although you'll need to pass some extraneous params.

You'd probably want to do a wrapper function to make life easier but, don't forget that the React.PropTypes are just functions themselves.

For example:

React.PropTypes.string(props, propName, componentName)

Where props is the entire props object for a component, propName is the name (and key) of the prop being checked, and componentName is the name of the component you're calling it from.

Although I think it would probably be better to roll your own as it would be a very small amount of code to do this yourself and it would shield you against any potential changes to how React.PropTypes work in future versions of React.

Upvotes: 3

Related Questions