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

import React from 'react';

// Example 1
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
var Hello = React.createClass({
    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

import React from 'react';

// Example 1
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
var Hello = React.createClass({
    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