Skip to content
Advertisement

React: How to change opacity of element by clicking button?

I want to change the opacity of headerInside element using React.

I came up with this idea, but with use of the vanilla JS.
How to write it using React hooks?

const menuHandler = () => {
  const element = document.querySelector('.headerInside');
  
  if (element.style.opacity === "1") {
    element.style.opacity = "0";
  } else {
    element.style.opacity = "1";
  }
}

The return() section looks like this:

<header>
  <button onClick={menuHandler} className="brgr">test</button>
  <div className="headerInside">
    ...  
  </div>
</header>

Advertisement

Answer

Zrna’s answer got the point. I wanna change it a little .

...
     <button onClick={() => setOpacity(1-opacity)} className="brgr">test</button>
...
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement