React component propTypes and default props

I like to encapsulate my React container components in ES6 classes together with propTypes and default props. So no const MyClass.propTypes outside the class scope. This can be achieved by using static class members supported by by several Babel presets.

First, you’ll need to first install Babel package that provides support for static class members:

yarn add --dev babel-preset-stage-1

Second, enable this Babel preset in your .babelrc:

{
  "presets": [
    ...
    "stage-1"
  ]
}

Finally, you can define your class like a boss:

import React, {Component} from 'react';
import PropTypes from "prop-types";

export default class MyContainer extends Component {
    static propTypes = {
        defaultProp1: PropTypes.array,
        defaultProp2: PropTypes.bool,
        defaultProp3: PropTypes.object
    };

    static defaultProps = {
        defaultProp1: [],
        defaultProp2: true,
        defaultProp3: {}
    };

    constructor() {
        super();
        this.state = {...MyContainer.defaultProps};
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *