Home > OS >  disabled={true} HTML button attribute does not work right in JavaScript React
disabled={true} HTML button attribute does not work right in JavaScript React

Time:09-21

Having issues with disabled={true} HTML button. App is in JavaScript React. I set button initial value disabled={true} .For example purposes I will call it id="button1". Once I click another button let's say id=button2, I re-enable my button1 with code document.getElementById('button1').disabled=false;. Button re-enables but once clicked it has no functionality, it looks like it is still disabled. What am I doing wrong ?

OK here is my simplified code:

 function App() {

  const approve = () => {
    console.log('test');
    
  };

  const filterWeek2 = () => {
    document.getElementById('approve').removeAttribute("disabled");
  };


  return (
    <div className="App">
          <nav>
            <ul className="nav-area">
              <li><button id="Week2" onClick={filterWeek2}>WEEK 2</button></li>
              <li><button id="approve" onClick={approve} disabled="disabled">APPROVE</button></li> 
            </ul>            
          </nav>    
        </div>
  );
}

export default withAuthenticator(App);

CodePudding user response:

The disabled is a boolean attribute, Its presence on an HTML elements disables the element. If it is present on the element, it will disable the HTML element, doesn't matter what value it has.

You have to remove the attribute using removeAttribute to make it editable

const disabled = document.querySelector(".disabled");
const normal = document.querySelector(".normal");

normal.addEventListener("click", () => {
  if (disabled.hasAttribute("disabled")) disabled.removeAttribute("disabled");
  else disabled.setAttribute("disabled", true);
})
<button disabled class="disabled">button</button>
<button class="normal">toggle</button>

Since you are using React, then you can toggle disabled using state. DEMO

disabled={active}

If active is true then the HTML element is disable else enabled.

  • Related