React component methods 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 methods only supported in createReactClass() API are 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.
  • Default props definition: Define a static property named defaultProps.

Noncompliant Code Example

View with compliant examples side by side
import 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 side
import 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 {
  static defaultProps = { greetName: 'hi' };
  render() {
    return <div>{this.props.greetName}</div>;
  }
}

Version

This rule was introduced in DeepScan 1.6.0-beta.

See

  • React Without ES6

  • React Warning: getInitialState was defined on Example1, 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 Example2, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.

Was this documentation helpful?