Search code examples
reactjsparent-childchildren

How to return child as a function in React after modifying the children with React.Children API?


I do have a component hierarchy like this

const Parent = ({ children }) => {
    const modifiedChildren = React.Children(children, (child) => {
        return React.cloneElement(child, {...child.props, extraProp: "someValue"})
    })
    return modifiedChildren
}

const App = () => {
    return (
        <Parent>
            <div>First</div>
            <div>Second</div>
            <div>Third</div>
        </Parent>
    )
}

It works fine, but I want to return children as a function from Parent component.

So my question is how to return children as a function from Parent, when you need to manipulate the children first by adding some props, etc

Edit

My target is something like this...

const Parent = ({ children }) => {
    const data = "some dynamic data"

    // here I want to modify children first, as I need to add some props dynamically
    
    return children(data)
}

const App = () => {
    return (
        <Parent>
            {(data) => (
                <>
                    <div>First</div>
                    <div>Second</div>
                    <div>Third</div>
                </>
            )}
        </Parent>
    )
}

Solution

  • If I understand your (updated) goals correctly, the following code should work:

    const Parent = ({ children }) => {
        const data = "some dynamic data";
        // Call any children specified as functions, passing in data
        let modifiedChildren = children.map((child) =>
          typeof child === 'function' ? child(data) : child);
        // modify modifiedChildren as necessary
        return modifiedChildren;
    }
    

    Function-specified children are just children. In your example, children will be an array of length 1, with the only item equal to a function. In the code above, I call any function-specified children. You could instead check whether the array is size 1 and has a single function, and then do something special in that case.