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

How to conditionally change visibility with React?

I am trying to change a div‘s visibility from hidden to visible using button click. But even when I am clicking the button, the visibility is not changing. I have logged the console after the clickHandler, and it still says false even after I set it to true inside the function. So far, I have this,

let clicked = false;
  //change image on fortune cookie click
  const clickHandler = (e) => {
    e.target.setAttribute(
      "src",
      "https://i.ibb.co/cksx7kr/kisspng-fortune-cookie-drawing-clip-art-fortune-cookie-5b237469209879-9079770415290502171335.png"
    );
    
    clicked = true;
  };
  console.log(clicked);
  return (
    <div className="App">
      <button onClick={clickHandler}>
        <img
          className="cookie"
          src="https://i.ibb.co/9YQV2qq/kisspng-fortune-cookie-biscuits-bakery-drawing-clip-art-fortune-cookies-5b0ec5e3013c23-3980054715276.png"
        />
      </button>
      <div
        className="fortuneMessage"
        style={{ visibility: clicked ? "visible" : "hidden" }}
      >
        {fortune}
      </div>
    </div>
  );

>Solution :

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

When you are using React, you need a state in order to have a DOM update. That would fork for you (don’t forget to import useState at the top of your file) :

  const [clicked, setClicked] = useState(false);
  const [src, setSrc] = useState("https://i.ibb.co/9YQV2qq/kisspng-fortune-cookie-biscuits-bakery-drawing-clip-art-fortune-cookies-5b0ec5e3013c23-3980054715276.png");
  
  //change image on fortune cookie click
  const clickHandler = (e) => {
    setSrc("https://i.ibb.co/cksx7kr/kisspng-fortune-cookie-drawing-clip-art-fortune-cookie-5b237469209879-9079770415290502171335.png");
    setClicked(true);
  };
  console.log(clicked);
  return (
    <div className="App">
      <button onClick={clickHandler}>
        <img
          className="cookie"
          src={src}
        />
      </button>
      <div
        className="fortuneMessage"
        style={{ visibility: clicked ? "visible" : "hidden" }}
      >
        {fortune}
      </div>
    </div>
  );
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