Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
React: Reorder children components

I have wrapper component which in some cases I need to reorder the position of only one of the children on it, sometimes I require to have ComponentX at the top, sometimes at the bottom. Is there any elegant way to achieve this? because I did it but replicating code.

const ComponentX = () => <h4>component x</h4>
const Component1 = () => <h4>component 1</h4>
const Component2 = () => <h4>component 2</h4>

const ComponentWrapper = ({xOnTop = false}) => {
  return (
    <div className="box">
       <h1>My components</h1>
        {xOnTop && <ComponentX />}
        <Component1 />
        <Component2 />
        {!xOnTop && <ComponentX />}
    </div>
  )
}

Here's my codepen

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What you have is perfectly fine, but I tried to come up with a different way to go about it and came up with this. So you can easily just invert the order of the component's keys using the xOnTop parameter.

const components = [
  <h4 key="1">component x</h4>,
  <h4 key="2">component 1</h4>,
  <h4 key="2">component 2</h4>
 ]

const ComponentWrapper = ({xOnTop = true}) => {
  components.sort((a, b) => xOnTop ? a.key - b.key : b.key - a.key)
  return (
    <div className="box">
      <h1>My components</h1>
      {components.map(c => c)}
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda