no-missing-button-type
Enforces an explicit 'type' attribute for 'button' elements.
Full Name in eslint-plugin-react-dom
react-dom/no-missing-button-typeFull Name in @eslint-react/eslint-plugin
@eslint-react/dom-no-missing-button-typeFeatures
š§
Presets
strict
strict-typescript
strict-type-checked
Rule Details
The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behavior you want inside a React application.
Allowed button types are submit, button, or reset.
Examples
Rendering a <button> without an explicit type
A button without a type attribute defaults to submit, which can unintentionally submit forms.
// Problem: missing explicit type; defaults to submit.
function MyComponent() {
return <button>Click me</button>;
// ^^^ Missing 'type' attribute on button component.
}// Recommended: explicitly declare the button type.
function MyComponent() {
return <button type="button">Click me</button>;
}Buttons inside forms
Inside a <form>, the default type="submit" can cause unexpected submissions. Always be explicit about whether a button submits the form or performs an independent action.
// Recommended: explicitly declare button types in forms
function Search() {
function search(formData: FormData) {
const query = formData.get("query");
alert(`You searched for '${query}'`);
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}Independent action buttons inside forms
Buttons that perform local UI actions (such as incrementing a counter) inside a form should use type="button" to prevent accidental form submission.
// Recommended: use type="button" for independent actions inside a form
import { useState } from "react";
function ShippingForm() {
const [count, setCount] = useState(1);
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
console.log(Object.fromEntries(formData), { count });
}
return (
<form onSubmit={handleSubmit}>
<label>
Number of items:
<button type="button" onClick={() => setCount((c) => c - 1)}>ā</button>
{count}
<button type="button" onClick={() => setCount((c) => c + 1)}>+</button>
</label>
<button type="submit">Submit</button>
</form>
);
}Versions
Resources
Further Reading
See Also
react-dom/no-missing-iframe-sandbox
Enforces an explicitsandboxattribute foriframeelements.