Try @eslint-react/kit@beta
logoESLint React

no-children-for-each

Disallows the use of 'Children.forEach' from the 'react' package.

Full Name in eslint-plugin-react-x

react-x/no-children-for-each

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-children-for-each

Presets

x recommended recommended-typescript recommended-type-checked strict strict-typescript strict-type-checked

Rule Details

Using Children is uncommon and can lead to fragile code. See common alternatives.

Examples

Iterating over children to augment them

Using Children.forEach to walk through and transform children is brittle because it relies on React's internal children structure. Prefer letting the parent handle iteration with standard array methods or restructuring your component API.

For example, if you need to interleave separators between children, let the parent pass an array directly and use .map():

// Recommended: accept data as an array prop and use standard JS methods
interface MyComponentProps {
  items: string[];
}

function MyComponent({ items }: MyComponentProps) {
  return (
    <>
      {items.map((item, index) => (
        <div key={item}>
          {item}
          {index < items.length - 1 && <hr />}
        </div>
      ))}
    </>
  );
}
// Problem: Using Children.forEach to iterate over and transform children
import React, { Children } from "react";

interface MyComponentProps {
  children: React.ReactNode;
}

function MyComponent({ children }: MyComponentProps) {
  const result = [];
  Children.forEach(children, (child, index) => {
    result.push(child);
    result.push(<hr key={index} />);
  });
  // ...
}

Versions

Resources

Further Reading


See Also

On this page