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

252
Visualizações
My react child callback returns the previous data (navbar)

I am learning React and I have a problem with my childCallback, for return data from child to parent.

I make a navbar and when I click on the navButton, the parent receive the name of the precedent button, I have to click two times for display the good data.

Here is my code :

//PARENT COMPONENT
export const Profil = () => {
  const [navActive, setNavActive] = useState("infos");

  const handleCallback = (childData, e) => {
    setNavActive(childData);
  };

  // View
  return (
    <div>
      <Navbar callback={handleCallback} />
      <Infos />
      <Gpg />
      {navActive}
    </div>
  );
};

//CHILD COMPONENT 
export const Navbar = ({ callback }) => {
  // Nav Items
  let nav = [
    { key: 1, name: "infos" },
    { key: 2, name: "gpg" },
    { key: 3, name: "compte" },
    { key: 4, name: "otp" },
    { key: 5, name: "journal" },
  ];

  // State
  const [activeTitle, setActiveTitle] = useState(nav[0].name);

  // Change the selected nav
  function selectNav(e) {
    let selected = e.target.innerText;
    setActiveTitle(selected);
  }

  const onTrigger = () => {
    callback(activeTitle);
  };

  // View
  return (
    <Nav tabs>
      {nav.map((item) => (
        <NavItem key={item.key} onClick={onTrigger}>
          <NavLink
            style={{ cursor: "pointer" }}
            onClick={selectNav}
            active={activeTitle === item.name}
          >
            {item.name}
          </NavLink>
        </NavItem>
      ))}
    </Nav>
  );
};

I don't know how to correct that.

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

0

Try to remove onclick from NavItem and call your callback function from selectNav function directly.

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem come from the setActiveTitle(selected) in Navbar, with console.log I test and the value is good before this.

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