0

Is it possible to access grand children through React.children.map(), if children are components ?

For exemple, a component :

const MyComponent = () => {
    return (
        <div className={'demo'}>Demo</div>
    )
}

Used in another component :

const WhateverComponent = () => {
    return (
        <Layout>
            <MyComponent />
            <MyComponent />
            <MyComponent />
        </Layout>
    )
}

now the

layout :

const Layout = ({children}) => (

    const iterateOverChildren = (children) => {
        return React.Children.map(children, (child) => {
            if (!React.isValidElement(child)) {
                return child
            }

            if (child.props.className && child.props.className.includes('demo')) {

                // Never pass here...

                return React.cloneElement(child, {
                    ...child.props,
                    onClick: closePreview,
                    children: iterateOverChildren(child.props.children),
                })
            }

            return React.cloneElement(child, {
                ...child.props,
                children: iterateOverChildren(child.props.children),
            })
        })
    }    

    return (
        <div>
            {iterateOverChildren(children)}
        </div>
    )
)

Do I make a mistake or is this by design that it's not possible ?

If I do this before the className test it work :

child = typeof child.type === 'function' ? child.type(child.props) : child

... but typescript hardly warn me :

This expression is not callable.   
Not all constituents of type 'JSXElementConstructor<any>' are callable.     
Type 'new (props: any) => Component<any, any, any>' has no call signatures.

Any advice ?

Nico
  • 1
  • 1

0 Answers0