Home > Net >  why is my if else statement returns true two times?
why is my if else statement returns true two times?

Time:07-07

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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 = () => {}
  • Related