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 the 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 the numeric value 0. For example, 0 will be rendered for array.length && <div>...</div> if the array is empty.

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

Noncompliant Code Example

View with compliant examples side by side
import { createRoot } from 'react-dom/client';

function App({ items }) {
  return (
    <div>
      {items.length && `(${items.join(', ')})`} {/* REACT_BAD_LENGTH_CHECK alarm */}
    </div>
  );
}

const root = createRoot(document.getElementById('root'));
root.render(<App items={[]} />);

Compliant Code Example

View with noncompliant examples side by side
import { createRoot } from 'react-dom/client';

function App({ items }) {
  return (
    <div>
      {items.length > 0 && `(${items.join(', ')})`}
    </div>
  );
}

const root = createRoot(document.getElementById('root'));
root.render(<App items={[]} />);

Version

This rule was introduced in DeepScan 1.3.0-beta.

See

Was this documentation helpful?