Skip to content
This repository was archived by the owner on Jul 31, 2026. It is now read-only.

Commit f573806

Browse files
cursoragentsvadrutk
andcommitted
fix(Button): default to non-submitting type
Co-authored-by: Swad K. <svadrutk@users.noreply.github.com>
1 parent 4fcbeac commit f573806

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

src/components/Button/index.test.tsx

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { render, screen } from "@testing-library/react";
2-
import { describe, it, expect } from "vitest";
1+
import { fireEvent, render, screen } from "@testing-library/react";
2+
import { describe, it, expect, vi } from "vitest";
33
import { Button } from "./";
44

55
describe("Button", () => {
@@ -20,4 +20,41 @@ describe("Button", () => {
2020
expect(text).toHaveClass("text-trim-cap");
2121
expect(text).not.toHaveClass("relative"); // button wrapper has 'relative', text span does not
2222
});
23+
24+
it("defaults to type button so it does not submit a parent form", () => {
25+
const onSubmit = vi.fn((event: React.FormEvent) => event.preventDefault());
26+
27+
render(
28+
<form onSubmit={onSubmit}>
29+
<Button>Discover</Button>
30+
</form>,
31+
);
32+
33+
const button = screen.getByRole("button", { name: "Discover" });
34+
expect(button).toHaveAttribute("type", "button");
35+
36+
fireEvent.click(button);
37+
expect(onSubmit).not.toHaveBeenCalled();
38+
});
39+
40+
it("preserves an explicit submit type", () => {
41+
render(<Button type="submit">Authorize</Button>);
42+
43+
expect(screen.getByRole("button", { name: "Authorize" })).toHaveAttribute(
44+
"type",
45+
"submit",
46+
);
47+
});
48+
49+
it("does not pass the default type to an asChild element", () => {
50+
render(
51+
<Button asChild>
52+
<a href="/discover">Discover</a>
53+
</Button>,
54+
);
55+
56+
expect(screen.getByRole("link", { name: "Discover" })).not.toHaveAttribute(
57+
"type",
58+
);
59+
});
2360
});

src/components/Button/index.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
213213
context = "product",
214214
asChild = false,
215215
className,
216+
type,
216217
onMouseEnter,
217218
onMouseLeave,
218219
onMouseDown,
@@ -486,6 +487,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
486487
onMouseMove={handleMouseMove}
487488
onMouseDown={handleMouseDown}
488489
onMouseUp={handleMouseUp}
490+
{...(!asChild ? { type: type ?? "button" } : {})}
489491
{...(asChild ? { isBrandVariant } : {})}
490492
{...props}
491493
>

0 commit comments

Comments
 (0)