The following works in Firefox 80.0 and Chromium 84.0.4147.89.
const fieldset = document.getElementById("fieldset");
const toggle = document.getElementById("toggle");
toggle.addEventListener("change", () => {
if (fieldset.hasAttribute("disabled")) {
fieldset.removeAttribute("disabled");
} else {
fieldset.setAttribute("disabled", true);
}
});
<form action="#">
<fieldset id="fieldset">
<legend>
<label>toggle <input id="toggle" type="checkbox" /></label>
</legend>
<input />
</fieldset>
</form>
However, when I try and do something similar in React, it doesn't work in Firefox. The onChange event appears not to fire once the fieldset is disabled.
function App() {
const [disabled, setDisabled] = React.useState(false);
const toggleDisabled = React.useCallback(() => {
setDisabled((disabled) => !disabled);
}, []);
return (
<form action="#">
<fieldset disabled={disabled}>
<legend>
<label>
toggle <input onChange={toggleDisabled} type="checkbox" />
</label>
</legend>
<input />
</fieldset>
</form>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The MDN fieldset article says:
[when the fieldset element is disabled] Note that form elements inside the
<legend>element won't be disabled.
W3C (Example B) and WHATWG also mention that the contents of the <legend> should not be disabled.
So I believe that the two pieces of code should behave in the same way: I should be able to toggle the disabled attribute using the checkbox.
How can I achieve the same effect in React on Firefox 80.0+?