diff --git a/.changeset/proud-readers-yell.md b/.changeset/proud-readers-yell.md new file mode 100644 index 0000000..08e5df8 --- /dev/null +++ b/.changeset/proud-readers-yell.md @@ -0,0 +1,5 @@ +--- +"@openfun/cunningham-react": patch +--- + +fix checkbox double onChange diff --git a/packages/react/src/components/Forms/Checkbox/index.spec.tsx b/packages/react/src/components/Forms/Checkbox/index.spec.tsx index cc7d57f..6cf9808 100644 --- a/packages/react/src/components/Forms/Checkbox/index.spec.tsx +++ b/packages/react/src/components/Forms/Checkbox/index.spec.tsx @@ -1,5 +1,5 @@ import userEvent from "@testing-library/user-event"; -import React from "react"; +import React, { useState } from "react"; import { render, screen } from "@testing-library/react"; import { Checkbox, @@ -134,4 +134,41 @@ describe("", () => { render(); expect(spyError).not.toHaveBeenCalled(); }); + + /** + * From this issue: https://github.com/openfun/cunningham/issues/175 + * The bug was that when clicking on the checkmark (svg) it was firing two onClick event to + * . + */ + it("can be unchecked when being controlled from a bigger parent", async () => { + const Wrapper = () => { + const [checked, setChecked] = useState(true); + return ( + // eslint-disable-next-line jsx-a11y/no-static-element-interactions + { + setChecked(!checked); + }} + style={{ width: "30%", background: "gainsboro", cursor: "pointer" }} + > + Full Card clickable + Checked = {checked ? "true" : "false"}| + + + ); + }; + + const user = userEvent.setup(); + render(); + const input: HTMLInputElement = screen.getByRole("checkbox"); + expect(input.checked).toEqual(true); + screen.getByText("Checked = true|"); + + // Uncheck by clicking on the SVG. + const checkmark = document.querySelector("svg.checkmark")!; + await user.click(checkmark); + expect(input.checked).toEqual(false); + screen.getByText("Checked = false|"); + }); }); diff --git a/packages/react/src/components/Forms/Checkbox/index.tsx b/packages/react/src/components/Forms/Checkbox/index.tsx index c1b7c7e..5393052 100644 --- a/packages/react/src/components/Forms/Checkbox/index.tsx +++ b/packages/react/src/components/Forms/Checkbox/index.tsx @@ -102,6 +102,7 @@ const Checkmark = () => ( viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" + onClick={(e) => e.stopPropagation()} > ( viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" + onClick={(e) => e.stopPropagation()} >