Generator object should not be used as a child of React element

  • REACT_BAD_CHILD_GENERATOR
  • Error
  • Medium
  • es6, react

This rule applies when a Generator object is used as a child of React element.

Generator objects are the return values of generator functions. Unlike other iterable objects such as array, Generator objects can be iterated only once. Iterating an already iterated Generator object results in an empty iteration.

During rendering, React may perform multiple iterations of iterable objects. For example, in development mode, key validation accompanies an iteration. In this case, nothing gets rendered and React outputs a warning message.

You can avoid this problem by converting the Generator object to an array using Array.from() or array spread operator like [...generatorObject].

Noncompliant Code Example

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

function* hello() {
    yield <div key="Hello">Hello</div>;
    yield <div key="There">There</div>;
}

export class Hello extends React.Component {
    render() {
        return (
            <div>
                {hello()} {/* REACT_BAD_CHILD_GENERATOR alarm because generator object is used as a child. */}
            </div>
        );
    }
}

Compliant Code Example

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

function* hello() {
    yield <div key="Hello">Hello</div>;
    yield <div key="There">There</div>;
}

export class Hello extends React.Component {
    render() {
        return (
            <div>
                {[...hello()]}
            </div>
        );
    }
}

Version

This rule was introduced in DeepScan 1.34.0.

See

  • Generator

  • React Warning: Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with Array.from() or the [...spread] operator before rendering. Keep in mind you might need to polyfill these features for older browsers.

Was this documentation helpful?