score:6

you can build a recursive wrapper component that replaces any children it has and wraps its children in the same way. the replacement will continue recursively until child elements have no more children.

here's an example of such a component. it substitutes <p> elements with <span> elements.

const recursivewrapper = props => {
    const wrappedchildren = react.children.map(
        props.children,
        child => {
            const type = child.type === 'p' ? 'span' : child.type
            if (child.props && child.props.children) {
                return react.cloneelement(
                    {
                        ...child,
                        type // substitute original type
                    },
                    {
                        ...child.props,
                        // wrap grandchildren too
                        children: (
                            <recursivewrapper>
                                {child.props.children}
                            </recursivewrapper>
                        )
                    }
                )
            }
            return child
        }
    )
    return (
        <react.fragment>
            {wrappedchildren}
        </react.fragment>
    )
}

you can use the same general idea to inject additional props as well.


Related Query

More Query from same tag