skip to Main Content

I have a button that I disabled via a boolean variable. The variable works on first load but when the variable is updated the disabled attribute stays. How do I update it so it gets removed?

My current code is like this:

var isDisabled = true;

return (
    <>
        <button onClick={() => isDisabled = false}>Enable Second Button</button>
        <button disabled={isDisabled}>Second Button</button>    
    </>
)

2

Answers


  1. Chosen as BEST ANSWER

    I fixed it by using React useState instead of normal variables. Instead of:

    var isDisabled = true;
    
    return (
        <>
            <button onClick={() => isDisabled = false}>Enable Second Button</button>
            <button disabled={isDisabled}>Second Button</button>    
        </>
    )
    

    I did

    const [isDisabled, setDisable] = useState(true);
    
    return (
        <>
            <button onClick={() => setDisable(false)}>Enable Second Button</button>
            <button disabled={isDisabled}>Second Button</button>    
        </>
    )
    

  2. Ensure that you have correctly bound the boolean variable to the disabled attribute of the button in your HTML code. The binding should be two-way so that changes to the variable reflect in the attribute and vice versa.

    <button id="myButton" [disabled]="isButtonDisabled">Click Me</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search