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

221
Visualizações
How can I set up state to allow one child component to render another

I have a main component which has two child components and six of each.

Something like this:

    <Main>
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component1 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
      <Component2 />
    </Main>

My goal is to be able to render a specific Component2 based on a toggle from Component 1.

So clicking the first Component1 would toggle the render of the first Component2

I've tried something like this in my main component:

  const [component2Visible, setcomponent2Visible] = useState([false, true, false, false, false, false])

But I don't think this is the right direction at all.

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

0

Here is an approach that I might employ:

// state variables to hold arguments to generate Component1 & Component2
// Component1 args have a prop named 'hideC2' (initially set to false)
const [comp1Args, setComp1Args] = useState([{hideC2: false, ...}, {hideC2: false, ....}, {}]);
const [comp2Args, setComp2Args] = useState([{}, {}, {}]);
.
.
.
// Iterate over the two args arrays to generate Components
// Use '.filter' on comp2Args to 'hide' those where 'hideC2' is set to true
return (
  <Main>
    {
      comp1Args.map((args, idx) => (
        <Component1
          key={idx}
          args={args}
          onToggleC2={() => setComp1Args(prev => {
            const curr = [...prev];
            curr[idx].hideC2 = !prev[idx].hideC2;
            return [...curr]
          })}
        />
      ))
    }
    {
      comp2Args
      .filter((el, idx) => (comp1Args[idx].hideC2 !== true))
      .map((args, idx) => (
        <Component2 key={idx} args={args}/>
      ))
    }
  </Main>
);
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