react/checked-requires-onchange-or-readonly
Require onChange or readOnly on an input that has checked
An <input> with checked is controlled by React. Without an onChange that updates the value, a click does nothing and the box looks broken. React also logs a warning for it.
The rule also reports an <input> with both checked and defaultChecked. The first says React controls the value, and the second says it doesn't. React.createElement("input", ...) is checked too.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react/checked-requires-onchange-or-readonly" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"react/checked-requires-onchange-or-readonly" = ["error", {
ignoreMissingProperties = false,
ignoreExclusiveCheckedAttribute = false,
}]Examples#
example.jsx1 problem
<input type="checkbox" checked={isSubscribed} />checked should be used with either onChange or readOnly.;example.jsx1 problem
<input type="checkbox" checked={isSubscribed} defaultChecked onChange={toggle} />Use either checked or defaultChecked, but not both.;example.jsxNo problems
const controlled = <input type="checkbox" checked={isSubscribed} onChange={toggle} />;
const fixed = <input type="checkbox" checked={isSubscribed} readOnly />;
const uncontrolled = <input type="checkbox" defaultChecked />;Options#
| Option | Default | What it does |
|---|---|---|
ignoreMissingProperties | false | Allow checked without onChange or readOnly. |
ignoreExclusiveCheckedAttribute | false | Allow checked together with defaultChecked. |
example.jsxwith
{ "ignoreMissingProperties": true }No problems<input type="checkbox" checked={isSubscribed} />;example.jsxwith
{ "ignoreExclusiveCheckedAttribute": true }No problems<input type="checkbox" checked={isSubscribed} defaultChecked onChange={toggle} />;