Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading