React 18 children array

Viewed 87

i have a Root component which contains multiple Panel components

export interface RootProps{
    children: React.ReactNode,
    className?: string,
    scheme?: 'light' | 'dark',
    activePanel: string
}

const Root = ({scheme, children, activePanel, className}: RootProps) => {
    const rootClassName = ['root']
    if(scheme === 'dark') rootClassName.push('dark')
    else rootClassName.push('light')
    if(className) className.split(' ').forEach(c => rootClassName.push(c))

    const panels = React.Children.toArray(children) as React.ReactElement[]

    return (
        <div className={rootClassName.join(' ')}>
            {panels.map((child: React.ReactElement) => {
                const panelClassName = ['panel-wrapper']
                if(child.props.id === activePanel) panelClassName.push('active')
                return <div className={panelClassName.join(' ')}>
                    {child}
                </div>
            })}
        </div>
    );
};
export interface PanelProps{
    children: React.ReactNode,
    id: string
}

const Panel = ({children}: PanelProps) => {
    const className = ['panel']
    return (
        <div className={className.join(' ')}>
            {children}
        </div>
    );
};

when i am using these components in a project

function App() {
    return (
        <Root activePanel={'root'}>
            <Panel id={'root'}>
                <Button>aboba</Button>
            </Panel>
            <Panel id={'not-root'}>
                <Button>aboba</Button>
            </Panel>
        </Root>
  );
}

there is a problem in <Root>: This JSX tag's 'children' prop expects a single child of type 'ReactElement<any, string | JSXElementConstructor>', but multiple children were provided.

1 Answers

instead of using React.ReactNode use React.ReactElement | React.ReactElement[]

Related