Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS component PropTypes - specify a function type with a set number parameters

I am specifying a required function proptype in a react (version 0.13.3) component...

var MyComponent = React.createClass({
    propTypes : {
        onClick : React.PropTypes.func.isRequired
    },

    handleClick(event) {
        this.props.onClick(event, clickCallback);
    },

    clickCallback() {
        console.log("foo");
    },

    render() {
        return <div onClick={this.handleClick}></div>
    }
});

export default MyComponent;

As you can see my onClick prop not only needs to be a function but needs to accept 2 arguments. is there any way to specify this using React PropTypes?

I have read the React docs entry on re-usable components and there seems to be only a way to define the shape of an object type but not a function type.

like image 648
danbahrami Avatar asked Oct 22 '15 10:10

danbahrami


People also ask

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.


2 Answers

You could try using a custom validator:

propTypes : {
    onClick : function(props, propName, componentName) {
        var fn = props[propName];
        if(!fn.prototype ||
           (typeof fn.prototype.constructor !== 'function' &&
            fn.prototype.constructor.length !== 2)) {
            return new Error(propName + 'must be a function with 2 args');
        }
    }
}
like image 195
edoloughlin Avatar answered Oct 04 '22 13:10

edoloughlin


Ok, I checked this a bit, and this could be the answer (unable to test it right now). So, you can pass validating functions for PropTypes, like:

propTypes : {
  onClick : function(props, propName, componentName) {
    if (!props.event || !props.callback) {
       return new Error('Too few arguments');
    }
  }
}

Check this article for details: http://developer.fortnox.se/blog/proptypes-in-react-js/

like image 23
Samuli Hakoniemi Avatar answered Oct 04 '22 12:10

Samuli Hakoniemi