Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

576
Vistas
React - replace child component in props.children

As seen in another question, it is possible to loop through the child elements using React.Children.map. I am looking for a way to recursively traverse the child tree (props.children.props.children...) and substitute certain elements with another type of element. It would happen in a higher-order-component's render function.

Any help and ideas are greatly appreciated!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda