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

164
Visualizações
Accessing React childs state

I have a React element that renders Child elements with a target state. this target state can change anytime and parent doesn't have access at the moment.

const Parent = () => {
  function getTarget(){
    //TODO
  }

  return(
    <Button>get target</Button>
    {children.map(c=>{
      <Child props={props}/>
    })}
  )
}

const Child = (props) => {
  //props stuff
  const [target, setTarget] = useState(null)
  // this target would be changed by user as they interact.
  
  return(
    //child elements
  )
}

what I'm trying to do is to get the target state of the Child using button in the Parent with following restraints:

  1. There can be variable amount of Child elements, but only one of them are visible at a time.

  2. The "get target" button has to be in Parent, the "target" state has to be initialized in child, and it's unknown.

because only on Child is active at a time, a solution that works for

return(
  <Button>get target</Button>
  <Child props={props}/>
)

is also fine.

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

0

const Parent = () => {
  const [activeTarget, setActiveTarget] = useState(null);

  const handleButton = () => {
    console.log(activeTarget);
  }

  return(
    <Button onClick={handleButton}>get target</Button>
    {children.map(c=>{
      <Child setActiveTarget={setActiveTarget} />
    })}
  )
}

const Child = ({setActiveTarget}) => {
  const [target, setTarget] = useState(null);
  
  // when the user interacts call 'setTarget' and 'setActiveTarget' to update both states
  
  // update parent state when child mounts
  useEffect(() => {
    setActiveTarget(target);
  }, [target]} // you can additionally add dependencies to update the parent state conditionally
  
  return(
    //child elements
  )
}

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