Home > database >  Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string |
Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string |

Time:11-25

I have a component declared as following:

const Wrapper = ({children}: {children: ReactElement[]}): ReactElement => {
  return (
    <div className="wrapper">
      {children}
    </div>
  );
};

This wrapper expects an array of ReactElement, for example:

<Wrapper>
  {items.map((item, index) => {
    return (
      <Item />
    )
  })}
</Wrapper>

This works fine, but when I want to add a div to the returned items list like following:

<Wrapper>
   <div /> {/* empty div for the first column */}
  {items.map((item, index) => {
    return (
      <Item />
    )
  })}
</Wrapper>

I get this error:

Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'.ts(2322)

How can I solve this ?

CodePudding user response:

The correct type for children in the usual Rect component sense is ReactNode (note it's not an array):

const Wrapper = ({ children }: { children: ReactNode }): ReactElement => {
    return <div className="wrapper">{children}</div>;
};

const Item = () => <div />;

const items = [1, 2, 3];
const x = (
    <Wrapper>
        <div />
        {items.map((item, index) => {
            return <Item />;
        })}
    </Wrapper>
);

Playground example

  • Related