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

266
Visualizações
why is my if else statement returns true two times?

so I am new to React and I am trying to learn the basics. I got stuck at a point, where I try to show/hide an element on a page. The problem is that when I click Show details, it works, but Hide details must be clicked 2 times in order to do what its supposed to do.

Can you help me understand this?

import React, { useState } from 'react'


const Playground2 = () => {

let visible = false;
const [details, showDetails] = useState();
const [buttonText, changeButtonText] = useState("Show details");

const toggleVisibility = () => {
    if (visible) {
        showDetails("");
        visible = false;
        console.log(visible);
        changeButtonText("Show details")

    } else {
        showDetails("Here are some details");
        visible = true;
        console.log(visible);
        changeButtonText("Hide details");
    }
}


return (
<>
    <section>
        <div className="container">
            <h1>Visibility Toggle</h1>
            <button onClick={toggleVisibility}>{buttonText}</button>
            <p>{details}</p>
        </div>
    </section>
</>
)
}

export default Playground2
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You should use the state in your condition. If you declare a variable like your visible one, this will be assigned on every render (every time you set the state with changeButtonText or showDetails. So every time will be set to false. You can simplify your component by doing:

import React, { useState } from 'react'


const Playground2 = () => {

const [visible, setVisible] = useState();

const toggleVisibility = () => {
    setVisible(prevState => !prevState)
}

const buttonText = visible ? 'Hide details' : 'Show details'
const details = 'Here are some details'

return (
  <>
    <section>
        <div className="container">
            <h1>Visibility Toggle</h1>
            <button onClick={toggleVisibility}>{buttonText}</button>
            {visible && <p>{details}</p>}
        </div>
    </section>
  </>
 )
}

export default Playground2
about 4 years ago · Juan Pablo Isaza Relatório

0

Well it'd solve your problem if you turn visibility to state as well.

What I think happening is that when you click on button, the visibility variable is turned to false but component isn't refreshed. In order for component to get refreshed, there must be some change in state.

Maybe try that. That should do the trick.

Tip: Variables like loading, visibility, modal closed/open should be state variables.

about 4 years ago · Juan Pablo Isaza Relatório

0

Move let visible = false out of the component body and this will work as expected, since you are putting visible inside Component, every time the component updates false will be stored in visible.

let visible = false
const Playground 2 = () => {}
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