Search code examples
reactjsintrospection

Can I inspect the proptypes of react component class if given an instance?


I'd love to access the propTypes of a class, e.g.

var Button = React.createClass({
  propTypes: {
    text: React.PropTypes.string,
    href: React.PropTypes.string
  },
  ...
})

...

var ButtonPropTypes = Button.propTypes

I'd expect to see something along the lines of

{ text: function(){...}, href: function(){...} }

But instead I get undefined. What am I doing wrong, and how can I get at the proptypes?


Solution

  • You should be able to access the proptypes statically as you are doing in your code. I put an example on jsfiddle and you can should be able to see the proptypes being printed in the console (they are functions)

    var Hello = React.createClass({
        getDefaultProps: function() {
            return {
              testing: 'default value'
            };
        },
        propTypes: {
            testing: React.PropTypes.string
        },
        render: function() {
            return (
                <div>        
                    <div>{this.props.name}</div>
                </div>
            )
        }
    });
    
    React.render(<Hello name="World" />, document.getElementById('container'));
    
    console.log(Hello.propTypes)
    

    https://jsfiddle.net/fj7ax0qr/