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 named defaultProps e.g. Hello.defaultProps = { greetName: 'hi' };

Noncompliant Code Example

// Example 1
import React from 'react';

class Hello 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>;
    }
}

// Example 2
import React from 'react';

class Hello 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

// Example 1
import React from 'react';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { greetName: 'hi' };
    }
    render() {
        return <div>{this.state.greetName}</div>;
    }
}

// Example 2
import React from 'react';

class Hello 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 Without ES6

  • 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.