Home > Software engineering >  UseState doesn't update state?
UseState doesn't update state?

Time:12-12

I have no idea why my useState doesn't change hidden from '' to 'hidden' in handleOnclick. Do you have anyidea ? Pls tell me..

    const [hidden,setHidden] = useState('hidden')
    const handleClick = () => {
        setHidden('hidden')
    }
  return (
    <div className="Create" onClick={()=>setHidden('')}>
         {console.log(hidden)}
         <div className={"unit "   hidden}>
              <i className="fas fa-times"
              onClick={handleClick}></i>
              <h2>Tạo A2</h2>
              <input type="text" placeholder="Mã.."/>
              <input type="text" placeholder="Mật khẩu.."/>
              <button>Tạo</button>
         </div>
    </div>
  );

CodePudding user response:

Because you setHidden to an empty string on the top level div. Any time you click the inner element you are also clicking within the outer element, so the event bubbles up and setHidden is called twice, the first time with your desired argument, the second time with an empty string. If you want to prevent bubbling, you need to add some logic to the function as shown here How can I prevent event bubbling in nested React components on click?

CodePudding user response:

This is caused by Event Bubbling. When you click on the i element that has an onClick handler attached to it, you are also implicitly triggering the onClick handler attached to the outer div element.

A way to handle this would be to stop the event from propagating to its parent by calling the event.stopPropagation() function in i's click handler, handleClick.

For more information about event bubbling and another concept called event capturing, you can visit the relevant section here. You can also play around with and better understand DOM events here.

  • Related