React component method only supported in createReactClass()
API should not be overridden in ES6 class component
- REACT_BAD_API_OVERRIDDEN
- Error
- Medium
- react
This rule applies when React component method only supported in createReactClass()
API is overridden in ES6 class component.
getInitialState()
and getDefaultProps()
methods are only supported in createReactClass()
API. When they are defined in ES6 class component, it may cause a problem because intended state initialization or default props definition might not be applied. Also React outputs a warning message.
If you need to use the methods in ES6 class component, try the following alternatives:
- State initialization: Initialize state in constructor.
defaultProps
definition: Define a static property nameddefaultProps
(e.g.Hello.defaultProps = { greetName: 'hi' };
).
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class Example1 extends React.Component {
getInitialState() { // REACT_BAD_API_OVERRIDDEN alarm because it is not supported in ES6 class component.
return { greetName: 'hi' };
}
render() {
return <div>{this.state.greetName}</div>;
}
}
export class Example2 extends React.Component {
static getDefaultProps() { // REACT_BAD_API_OVERRIDDEN alarm because it is not supported in ES6 class component.
return { greetName: 'hi' };
}
render() {
return <div>{this.props.greetName}</div>;
}
}
Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
export class Example1 extends React.Component {
constructor(props) {
super(props);
this.state = { greetName: 'hi' };
}
render() {
return <div>{this.state.greetName}</div>;
}
}
export class Example2 extends React.Component {
render() {
return <div>{this.props.greetName}</div>;
}
}
Hello.defaultProps = { greetName: 'hi' };
Version
This rule was introduced in DeepScan 1.6.0-beta.
See
React Warning: getInitialState was defined on a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
React Warning: getDefaultProps was defined on a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.
React Warning: getDefaultProps is only used on classic React.createClass definitions. Use a static property named
defaultProps
instead.