I have this button component in my react js 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 the button is not triggering alert message after removing the atribute inside the browser?
CodePudding user response:
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.
CodePudding user response:
As per your code, I can see that you did not remove the disabled attribute. You only removed the {true} part. Keeping the disabled attribute, even if it is not set to true, will still disable the button, which is why it is not getting triggered. Try this :-
<button onClick={() => alert("hi")}>test</button>