Removing disabled HTML attribute from a button does not allow to click it

Issue

I have this button component in my React application:

<button onClick={() =>alert('hi')} disabled={true}>test</button>

I expected when I will remove disabled attribute in browser like:

<button disabled>test</button>

to:

<button>test</button>

The button should be clicked and alert should appear but it did not happen.

Why is the button not triggering alert message after removing the attribute inside the browser?

Solution

The <button> you render with react is not the actual DOM element but a built-in component, that manages its state internally. So the props you pass to that component only get reflected in the DOM when react re-renders it when props or state have changed.

But React doesn’t know you removed the disabled attribute in the DOM. From the perspective of react, the button is still disabled and click events are therefore suppressed. When managing the DOM with react you should not try to manipulate the DOM from outside as react will not be aware of any changes and they will be overridden with every render.

Also events on built-in components are managed by reacts own event handling. So the handler you passed to the <button> component is not the same as if you provided it directly to the DOM element.

Answered By – trixn

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.