🐛(react) fix props not recognized on the input element

The props propagation was adding unknown props to the input element,
which was causing an error warning to be displayed in the console.
This commit is contained in:
Anthony Le Courric
2023-09-11 11:40:15 +02:00
committed by Anthony LC
parent 8086a48672
commit c7000f37d2
9 changed files with 190 additions and 27 deletions

View File

@@ -1,9 +1,16 @@
import { render, screen } from "@testing-library/react";
import React from "react";
import userEvent from "@testing-library/user-event";
import { Switch } from ":/components/Forms/Switch/index";
import { FieldProps } from "../Field";
import { Switch, SwitchOnlyProps } from ":/components/Forms/Switch/index";
const spyError = vi.spyOn(global.console, "error");
describe("<Switch/>", () => {
afterAll(() => {
spyError.mockRestore();
});
it("renders and can be checked", async () => {
const user = userEvent.setup();
render(<Switch label="Newsletter" />);
@@ -132,4 +139,21 @@ describe("<Switch/>", () => {
expect(input.checked).toEqual(false);
screen.queryByText("Value: false.");
});
it("checks the props doesn't create error warning", async () => {
const propsInput: Required<FieldProps & SwitchOnlyProps> = {
label: "First name",
fullWidth: true,
className: "c__field--full-width",
compact: false,
state: "default",
text: "my text",
textItems: ["my text item 1", "my text item 2"],
rightText: "my right text",
labelSide: "right",
};
render(<Switch {...propsInput} />);
expect(spyError).not.toHaveBeenCalled();
});
});

View File

@@ -2,14 +2,27 @@ import React, { InputHTMLAttributes, forwardRef } from "react";
import classNames from "classnames";
import { Field, FieldProps } from ":/components/Forms/Field";
export type SwitchOnlyProps = {
label?: string;
labelSide?: "left" | "right";
};
export type SwitchProps = InputHTMLAttributes<HTMLInputElement> &
FieldProps & {
label?: string;
labelSide?: "left" | "right";
};
FieldProps &
SwitchOnlyProps;
export const Switch = forwardRef<HTMLInputElement, SwitchProps>(
({ label, labelSide = "left", ...props }: SwitchProps, ref) => {
const {
compact,
fullWidth,
rightText,
state,
text,
textItems,
...inputProps
} = props;
return (
<label
className={classNames(
@@ -26,7 +39,7 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(
<div className="c__checkbox__container">
{label && <div className="c__checkbox__label">{label}</div>}
<div className="c__switch__rail__wrapper">
<input type="checkbox" {...props} ref={ref} />
<input type="checkbox" {...inputProps} ref={ref} />
<div className="c__switch__rail" />
</div>
</div>