Skip to content

Rule proposal: react/no-react-children for preventing usage of legacy React.Children #20015

@connorshea

Description

@connorshea

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:

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} />);
  });
  // ...
}

Metadata

Metadata

Assignees

Labels

Priority

None yet

Start date

None yet

Target date

None yet

Effort

None yet

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions