Properties of the uninitialized this.props should not be accessed

  • REACT_UNINITIALIZED_PROPS
  • Error
  • High
  • react

This rule applies when properties of the uninitialized this.props are accessed.

Accessing properties of the uninitialized this.props causes a TypeError exception because this.props is always undefined in the below cases.

  1. Properties are accessed in the component constructor when super() is not called with the first argument of the constructor before any other statement.
  2. Properties are accessed in getDefaultProps(). (getDefaultProps() is called before any instances are created and thus cannot rely on this.props.)

Noncompliant Code Example

View with compliant examples side by side
// Example 1
import React from 'react';

export class SayHello extends React.Component {
    constructor(props) {
        super();
        this.state = { x: this.props.x }; // REACT_UNINITIALIZED_PROPS alarm because above 'super' is not called with 'props'. (TypeError: Cannot read property 'x' of undefined)
    }
    render() {
        return (<div><Hello /> {this.state.x}</div>);
    }
}

// Example 2
import createReactClass from 'create-react-class';

export var Hello = createReactClass({
    getDefaultProps: function () {
        return {
            initialMessage: this.props.message // REACT_UNINITIALIZED_PROPS alarm because 'this.props' is undefined. (TypeError: Cannot read property 'message' of undefined)
        };
    },
    getInitialState: function () {
        return { message: this.props.initialMessage };
    },
    render: function () {
        return (<span>{this.state.message}</span>);
    }
});

Compliant Code Example

View with noncompliant examples side by side
// Example 1
import React from 'react';

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

// Example 2
import createReactClass from 'create-react-class';

export var Hello = createReactClass({
    getDefaultProps: function () {
        return {
            initialMessage: "Hello"
        };
    },
    getInitialState: function () {
        return { message: this.props.initialMessage };
    },
    render: function () {
        return (<span>{this.state.message}</span>);
    }
});

Version

This rule was introduced in DeepScan 1.5.0-beta.

See

Was this documentation helpful?