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

226
Vistas
How to dynamically create a component tree in React based on an array that contains components?

I have a components array.

const components = [
  A,
  B,
  C,
]

Then I want to render this components like this:

return (
  <A>
    <B>
      <C>
      </C>
    </B>
  </A>
)

But I can add a new component or switch the order of the components. I want to render this component tree in the same order as the components array.

So how can I dynamically create a component tree based on the components array?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

at least one

Write a recursive function, nest. At least one component is required -

const nest = ([T, ...more]) =>
  more.length == 0
    ? <T />
    : <T>{nest(more)}</T>

Use it in your components like this -

function MyComp(props) {
  return nest([A, B, C])
}

possibly zero

If you want the possibility to support an empty array, this is safest -

const nest = ([T, ...more]) =>
  T == null
    ? null
    : <T>{nest(more)}</T>
nest([]) // => null
nest([A,B,C]) // => <A><B><C/></B></A>

with props

If you want to supply props to the components, you can use a similar technique -

const nest = ([T, ...more], [p, ...props]) =>
  T == null || p == null
    ? null
    : <T {...p}>{nest(more, props)}</T>
nest([A,B,C], [{active: true}, {onClick: console.log}, {}])
<A active={true}>
  <B onClick={console.log}>
    <C />
  </B>
</A>

alternative

If props are needed, a better solution might be to colocate the props with the components using continuations -

const nest = ([T, ...more]) =>
  T == null
    ? null
    : T(nest(more))
nest([ 
  _ => <A active={true}>_</A>,
  _ => <B onClick={console.log}>_</B>,
  _ => <C/>
])
<A active={true}>
  <B onClick={console.log}>
    <C />
  </B>
</A>
about 4 years ago · Juan Pablo Isaza 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