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 following static properties which applied to all instances of the component once defined as static.

  1. propTypes
  2. contextTypes
  3. getDerivedStateFromProps()

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

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';
import PropTypes from 'prop-types';

export 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>;
    }
}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';
import PropTypes from 'prop-types';

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

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.

  • React Warning: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.

Was this documentation helpful?