-
-
Notifications
You must be signed in to change notification settings - Fork 877
Description
React.Children is a module that exists in React, but is strongly discouraged by its docs and marked as Legacy.
eslint-plugin-react does not have a rule for banning this, however eslint-plugin-react-x (aka @eslint-react) does have rules for this. It actually has 5 of them, for 5 separate methods:
- https://www.eslint-react.xyz/docs/rules/no-children-count
- https://www.eslint-react.xyz/docs/rules/no-children-for-each
- https://www.eslint-react.xyz/docs/rules/no-children-map
- https://www.eslint-react.xyz/docs/rules/no-children-only
- https://www.eslint-react.xyz/docs/rules/no-children-to-array
I would rather keep it simple and just add a rule to ban React.Children entirely, but we could implement all 5 of those if we feel strongly about it for some reason.
The goal of the rule would be to ban all usage of React.Children and import { Children } from 'react';. I realize that this can be accomplished to an extent by using the no-restricted-imports rule (or via JS Plugins with the plugin noted above), but I think it's extremely valuable to have best practices built into the linter where possible so users (and/or their AIs) don't have to stumble into these problems themselves and set up infrastructure for it themselves.
Examples of violations:
import React, { Children } from "react";
function MyComponent({ children }: MyComponentProps) {
const result = Children.toArray(children);
result.reverse();
// ...
}
const mappedChildren = Children.map(children, child =>
<div className="Row">
{child}
</div>
);
function MyComponent({ children }: MyComponentProps) {
const element = Children.only(children);
// ...
}
function MyComponent({ children }: MyComponentProps) {
return (
<>
<h1>Total rows: {Children.count(children)}</h1>
</>
);
}
function MyComponent({ children }: MyComponentProps) {
const result = [];
Children.forEach(children, (child, index) => {
result.push(child);
result.push(<hr key={index} />);
});
// ...
}