Specify An Explicit Type On A JSX button
ID |
javascript.jsx_button_type |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
jsx, reliability |
Rationale
A <button> with no type defaults to submit. Inside a form that turns an ordinary-looking
button into one that submits the form on a click — or on Enter anywhere in the form, since the
first submit button is the implicit default.
In React the consequence is sharper than in plain HTML: the page reloads, the component tree is
thrown away and the onClick handler’s state update is lost, which reads at the desk as "my
handler does not run". Declaring the intended type makes the element’s role explicit and costs one
attribute.
Only the DOM tag is judged. <Button> is a component whose rendered markup is not visible here,
and it commonly sets the default itself. Any declared value satisfies the rule, computed ones
included: the point is that the choice was made. An element that spreads an object into its
attributes is left alone, since type may arrive at runtime.
<button onClick={save}>Save</button> // FLAW - defaults to submit
<button className="icon" /> // FLAW - same
<button type="button" onClick={save}>Save</button> // OK
<button type={kind}>Save</button> // OK - computed, but declared
<Button onClick={save}>Save</Button> // OK - a component, markup unknown
Remediation
Write the type the button is for: type="button" for one that only runs its handler,
type="submit" for the one that submits the form, type="reset" for one that clears it. A button
outside any form still wants type="button", so that wrapping it in a form later does not change
what it does.