Reputation: 65
I'm quite new to React and tried taking a shot at creating a Navbar. But I ran into a problem which I can't seem to wrap my head around I've got following Component:
interface Props {
children: React.ReactElement<Navitem>[];
}
export class Navbar extends React.Component<Props, {}> {
render() {
return (
<div className={"navbar"}>
{this.props.children}
</div>
);
}
}
aswell as a Navitem component:
interface Props{
label?: string;
}
export class Navitem extends React.Component<Props, {}>{
render(){
return <p>{this.props.label}</p>
}
}
When trying to create a the navbar tho as follows:
<Navbar>
<Navitem label={"Item 1"}/>
</Navbar>
I get this error:
No overload matches this call.
This JSX tag's 'children' prop expects type 'ReactElement<Navitem, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>[] | ... 6 more ... | (ReactElement<...>[] & ReactPortal)' which requires multiple children, but only a single child was provided.
This JSX tag's 'children' prop expects type 'ReactElement<Navitem, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>[] | ... 6 more ... | (ReactElement<...>[] & ReactPortal)' which requires multiple children, but only a single child was provided. TS2769
When trying it with multiple Navitems as the error message suggests it works.
So finally to my question: Is it not possible to have an children prop array with only one element in it or am I just missing something. Any help is appreciated!
(FYI I know I could do
children: React.ReactElement<Navitem>[] | React.ReactElement<Navitem>;
but then I would have to check if it was a single object or an array everytime I want to do something with it)
Upvotes: 2
Views: 1192
Reputation: 61
I had this same problem for my component when I try to pass single child to array of children type. We can avoid this error by manually create array with single child and key in JSX.
<Navbar>
{[<Navitem key="1" label={"Item 1"}/>]}
</Navbar>
Upvotes: 1