soywod
soywod

Reputation: 4520

React children[] issue with TypeScript

I have one component Radio:

import { RadioItemProps } from './Item';

type Props = {
  children: ReactElement<RadioItemProps>[];
};

export default function Radio(props: Props) {
  return props.children;
}

and a component RadioItem that should be a direct child of Radio:

export type RadioItemProps = {
  value: string;
  children: ReactText;
};

export default function RadioItem(props: RadioItemProps) {
  return <input type="radio" name="xxx" value={props.value} />;
}

When I use them:

<Radio>
  <RadioItem value="option-1">Option 1</RadioItem>
  <RadioItem value="option-1">Option 1</RadioItem>
</Radio>

I have the TypeScript error: JSX element type 'ReactElement<RadioItemProps, ...>[]' is missing the following properties f rom type 'Element': type, props, key

If I change the children type to ReactElement<RadioItemProps>, and add only one child, it works. But once I put the array, I get this error.

What I am missing?

"typescript": "^3.2.2",
"react": "16.7.0-alpha.2",
"react-dom": "16.7.0-alpha.2",
"@types/react": "^16.8.3",
"@types/react-dom": "^16.0.11",

Upvotes: 1

Views: 4813

Answers (1)

soywod
soywod

Reputation: 4520

I just found the issue... it's because of:

export default function Radio(props: Props) {
  return props.children;
}

I had to change it to:

export default function Radio(props: Props) {
  return (
    <Fragment>{props.children}</Fragment>
  )
}

It seems that the children (typed as array) can't be returned directly. Which is strange, because this works:

export default function Radio(props: Props) {
  return ['lol'];
}

It was a tricky one...

Upvotes: 3

Related Questions