this object should not be used in React function components

  • REACT_FUNC_COMPONENT_INVALID_THIS
  • Error
  • Medium
  • react

This rule applies when this object is used in a React function component.

this is bound to an undefined value in a function component unlike the this object of a class component, which represents the component instance. Accessing properties of this in a function component will result in a TypeError exception.

Therefore, it is likely that a programmer has mistaken the function component for a class component.

Noncompliant Code Example

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

function Hello(props) {
    return (
        <div>Hello, {this.props.name}</div> // REACT_FUNC_COMPONENT_INVALID_THIS alarm
    );
}
Hello.propTypes = {
    name: PropTypes.string
};

Compliant Code Example

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

function Hello(props) {
    return (
        <div>Hello, {props.name}</div>
    );
}
Hello.propTypes = {
    name: PropTypes.string
};

Version

This rule was introduced in DeepScan 1.27.0.