I have a component that can accept React children
as either a node or an array of nodes. I want to be able to detect if children
is an array of nodes, but I am getting the following Typescript error:
TS2339: Property 'length' does not exist on type 'string | number | true | {} | ReactElement<any, string | ((props: any) => ReactElement<any, any> | null) | (new (props: any) => Component<any, any, any>)> | ... 47 more ... | (ReactNode[] & ReactPortal)'. Property 'length' does not exist on type 'number'.
Is there a way in Typescript where I detect if children
has length? Thanks.
import React from 'react';
interface Props {
children: React.ReactNode | React.ReactNode[];
}
const SampleComponent: React.FC<Props> = ({ children }) => {
if (children && children.length) {
return children.map((child) => (
<div>{child}</div>
));
}
return children;
};
export default SampleComponent;