Your Button component should default to type="button"
Published on in JavaScript, React and TypeScript
A <button>
element defaults to type="submit"
which can cause accidental form submissions.
Make type="button"
the default in your Button component
to make your life easier.
Table of contents
type="button"
vs type="submit"
A <button>
element without a type
attribute
defaults to type="submit"
.
Clicking a submit button associated with a <form>
submits the form
unless event.preventDefault()
is called.
A <button>
element with type="button"
on the other hand
does nothing by default when clicked.
Calling event.preventDefault()
does nothing
because there's no default action to prevent.
Setting your Button component to default to type="button"
allows you to not worry about:
- accidental form submissions
- having to remember call
event.preventDefault()
.
Also, using <Button type="submit">
makes it explicit that it's a submit button.
Example with React and TypeScript
type Props = React.ButtonHTMLAttributes<HTMLButtonElement> & { type?: 'submit' }
const Button = ({ children, type, ...props }: Props) => (
<button {...props} type={type || 'button'}>
{children}
</button>
)
// Usage:
<Button /> // Defaults to `type="button"`
<Button type="submit" />
The type
prop's value in React.ButtonHTMLAttributes<HTMLButtonElement>
is "submit" | "button" | "reset" | undefined
.
I'm restricting the value to "submit" | undefined
,
so that only type="submit"
is allowed.
(Omitting the prop is also allowed.)
type="button"
is not allowed because it's the default, so it would be unnecessary noise.type="reset"
is not allowed because reset buttons (i.e. buttons that empty the whole form) are so stupid. 🤡 Not on my watch!