Static properties of a React class component should not be defined as instance properties
- REACT_STATIC_PROPERTY_IN_INSTANCE
- Error
- Medium
- react
This rule applies when the static property of a React class component is defined as an instance property.
React provides the following static properties which apply to all instances of the component once defined as static.
contextType
defaultProps
getDerivedStateFromProps()
getDerivedStateFromError()
If these properties are defined as instance properties of the class, React ignores them and outputs a warning message.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class Hello extends React.Component {
defaultProps = { msg: 'Hello' } // REACT_STATIC_PROPERTY_IN_INSTANCE alarm
render() {
return <h1>{this.props.msg} there!</h1>;
}
}
Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
export class Hello extends React.Component {
static defaultProps = { msg: 'Hello' }
render() {
return <h1>{this.props.msg} there!</h1>;
}
}
Version
This rule was introduced in DeepScan 1.6.0-beta.
See
React Warning: contextType was defined as an instance property on Hello. Use a static property to define contextType instead.
React Warning: Setting defaultProps as an instance property on Hello is not supported and will be ignored. Instead, define defaultProps as a static property on Hello.
React Warning: Hello: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.