length property itself should not be checked in the code for React child element

  • REACT_BAD_LENGTH_CHECK
  • Error
  • Medium
  • react

This rule applies when length property itself is checked in the code for React child element.

In React, a child element specified as undefined, null, true or false is excluded from rendering. This feature is often used to render an element conditionally, e.g. cond && <div>...</div>.

However, the exclusion is not applied to numeric value 0. For example, 0 will be rendered for array.length && <div>...</div> if array is empty.

This problem is fixed by using a boolean-valued expression such as array.length > 0 instead of checking length property itself.

Noncompliant Code Example

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

export class Foo extends React.Component {
    render() {
        return (
            <div>
                {this.props.items.length && `(${this.props.items.join(', ')})`} {/* REACT_BAD_LENGTH_CHECK alarm */}
            </div>
        );
    }
}

Compliant Code Example

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

export class Foo extends React.Component {
    render() {
        return (
            <div>
                {this.props.items.length > 0 && `(${this.props.items.join(', ')})`}
            </div>
        );
    }
}

Version

This rule was introduced in DeepScan 1.3.0-beta.

See

Was this documentation helpful?