6 мая 2017 г.

How to properly define propTypes for React component

Wrong way

// Wrong! propTypes should be either static property or static property getter
class TextWrongES6 extends Component {
    static propTypes() {
        return { children: PropTypes.string };
    }

    static defaultProps() {
        return { children: 'Hello World!' };
    }

    render() {
        return <p>{this.props.children}</p>;
    }
}

Right ways

// The ES5 way
var TextES5Way = React.createClass({
    propTypes: { children: PropTypes.string },

    getDefaultProps: function() {
        return { children: 'Hello World!' };
    },

    render: function() {
        return <p>{this.props.children}</p>;
    }
});

// The ES6 way - ES6 class + class properties
class TextES6Way1 extends Component {
    render() {
        return <p>{this.props.children}</p>;
    }
}
TextES6Way1.propTypes = { children: PropTypes.string };
TextES6Way1.defaultProps = { children: 'Hello World!' };

// The ES6 way - ES6 class + ES5 getters
class TextES6Way2 extends Component {
    static get propTypes() {
        return { children: PropTypes.string };
    }

    static get defaultProps() {
        return { children: 'Hello World!' };
    }

    render() {
        return <p>{this.props.children}</p>;
    }
}

// The ES7 way - static property initializers (experimental feature)
class TextES7Way extends Component {
    static propTypes = { children: PropTypes.string };
    static defaultProps = { children: 'Hello World!' };

    render() {
        return <p>{this.props.children}</p>;
    }
}

// The Stateless Functional Component way
const Text = (props) => <p>{props.children}</p>;
Text.propTypes = { children: PropTypes.string };
Text.defaultProps = { children: 'Hello World!' };