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 sideimport { createRoot } from 'react-dom/client';
function* hello() {
yield <div key="Hello">Hello</div>;
yield <div key="There">There</div>;
}
function App() {
return (
<div>
{hello()} {/* REACT_BAD_CHILD_GENERATOR alarm */}
</div>
);
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
Compliant Code Example
View with noncompliant examples side by sideimport { createRoot } from 'react-dom/client';
function* hello() {
yield <div key="Hello">Hello</div>;
yield <div key="There">There</div>;
}
function App() {
return (
<div>
{[...hello()]}
</div>
);
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
Version
This rule was introduced in DeepScan 1.34.0.
See
React Warning: Using Iterators 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. You can also use an Iterable that can iterate multiple times over the same items.