HTML forms have a very logical and useful behavior about how form values and default values are handled. For inputs whose value is equal to default value, changing default value automatically updates value too.
However, React breaks that behavior. It actually applies the correct DOM attribute/property, but overrides browser's behavior of setting DOM value automatically even for uncontrolled inputs.
Comparison of React vs Vanilla JS:
React:
import React from 'react';
export function App() {
const [isDefaultChecked, setIsDefaultChecked] = React.useState(false);
React.useEffect(() => {
const id = setTimeout(() => setIsDefaultChecked(true), 100);
return () => clearTimeout(id);
}, []);
return <input type="checkbox" defaultChecked={isDefaultChecked} />;
}
Vanilla JS:
document.body.innerHTML = '<input type="checkbox" />';
const input = document.querySelector('input');
setTimeout(() => {
// either set prop
input.defaultChecked = true;
// or add it as attr
input.setAttribute('checked', '');
}, 100);
Top comments (0)