React static property should not be defined as an instance property

  • REACT_STATIC_PROPERTY_IN_INSTANCE
  • Error
  • Medium
  • react

This rule applies when the React static property is defined as an instance property.

React provides two static properties (propTypes and contextTypes) which applied to all instances of the component once defined as static.

When these properties are defined as instance properties in ES6 class component, React outputs a warning message.

Noncompliant Code Example

import React from 'react';
import PropTypes from 'prop-types';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.propTypes = { name: PropTypes.string }; // REACT_STATIC_PROPERTY_IN_INSTANCE alarm because 'propTypes' is defined as an instance property.
        this.contextTypes = {}; // REACT_STATIC_PROPERTY_IN_INSTANCE alarm because 'contextTypes' is defined as an instance property.
    }
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}
ReactDOM.render(<Hello name="DeepScan" />, document.getElementById("root"));

Compliant Code Example

import React from 'react';
import PropTypes from 'prop-types';

class Hello extends React.Component {
    static contextTypes = {};
    constructor(props) {
        super(props);
    }
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}
Hello.propTypes = {
    name: PropTypes.string
};
ReactDOM.render(<Hello name="DeepScan" />, document.getElementById("root"));

Version

This rule was introduced in DeepScan 1.6.0-beta.

See

  • propTypes

  • contextTypes

  • React Warning: propTypes was defined as an instance property on Hello. Use a static property to define propTypes instead.

  • React Warning: contextTypes was defined as an instance property on Hello. Use a static property to define contextTypes instead.