no-children-to-array
Rule category
Restriction.
What it does
Checks usage of React.Children.toArray.
Why is this bad?
Using Children.toArray is uncommon and can lead to fragile code. See common alternatives.
Examples
Failing
import React, { const Children: {
map<T, C>(children: C | readonly C[], fn: (child: C, index: number) => T): C extends null | undefined ? C : Array<Exclude<T, boolean | null | undefined>>;
forEach<C>(children: C | readonly C[], fn: (child: C, index: number) => void): void;
count(children: any): number;
only<C>(children: C): C extends any[] ? never : C;
toArray(children: React.ReactNode | React.ReactNode[]): Array<Exclude<React.ReactNode, boolean | null | undefined>>;
}
Maintainer's note: Sync with
{@link
ReactChildren
}
until
{@link
ReactChildren
}
is removed.Children } from "react";
interface ExampleProps {
ExampleProps.children: React.ReactNodechildren: React.type React.ReactNode = string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal | null | undefinedRepresents all of the things React can render.
Where
{@link
ReactElement
}
only represents JSX, `ReactNode` represents everything that can be rendered.ReactNode;
}
function function Example({ children }: ExampleProps): voidExample({ children: React.ReactNodechildren }: ExampleProps) {
const const result: (string | number | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal)[]result = const Children: {
map<T, C>(children: C | readonly C[], fn: (child: C, index: number) => T): C extends null | undefined ? C : Array<Exclude<T, boolean | null | undefined>>;
forEach<C>(children: C | readonly C[], fn: (child: C, index: number) => void): void;
count(children: any): number;
only<C>(children: C): C extends any[] ? never : C;
toArray(children: React.ReactNode | React.ReactNode[]): Array<Exclude<React.ReactNode, boolean | null | undefined>>;
}
Maintainer's note: Sync with
{@link
ReactChildren
}
until
{@link
ReactChildren
}
is removed.Children.function toArray(children: React.ReactNode | React.ReactNode[]): Array<Exclude<React.ReactNode, boolean | null | undefined>>toArray(children: React.ReactNodechildren);
const result: (string | number | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal)[]result.Array<string | number | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal>.reverse(): (string | number | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal)[]Reverses the elements in an array in place.
This method mutates the array and returns a reference to the same array.reverse();
// ...
}