diff --git a/packages/react/src/components/Forms/Switch/index.mdx b/packages/react/src/components/Forms/Switch/index.mdx index 3fa5768..0df129c 100644 --- a/packages/react/src/components/Forms/Switch/index.mdx +++ b/packages/react/src/components/Forms/Switch/index.mdx @@ -99,6 +99,14 @@ In order to control the value of the switch, you can use the `checked` or `defau +## Usage with react-hook-form + +You can use this input with [react-hook-form](https://react-hook-form.com/docs) + + + + + ## Props The props of this component are as close as possible to the native checkbox component. You can see the list of props below. diff --git a/packages/react/src/components/Forms/Switch/index.stories.tsx b/packages/react/src/components/Forms/Switch/index.stories.tsx index eefa847..e2376ce 100644 --- a/packages/react/src/components/Forms/Switch/index.stories.tsx +++ b/packages/react/src/components/Forms/Switch/index.stories.tsx @@ -1,7 +1,15 @@ +import { yupResolver } from "@hookform/resolvers/yup"; import { Meta } from "@storybook/react"; +import { useForm } from "react-hook-form"; +import * as Yup from "yup"; import React from "react"; import { Switch } from ":/components/Forms/Switch/index"; import { Button } from ":/components/Button"; +import { + getFieldState, + getFieldErrorMessage, + onSubmit, +} from ":/tests/reactHookFormUtils"; export default { title: "Components/Forms/Switch", @@ -122,6 +130,49 @@ export const Controlled = { }, }; +export const ReactHookForm = () => { + interface SwitchExampleFormValues { + terms: boolean; + } + + const switchExampleSchema = Yup.object().shape({ + terms: Yup.boolean() + .required() + .oneOf([true], "You have to accept the terms of use"), + }); + + const { register, handleSubmit, formState } = + useForm({ + defaultValues: { + terms: false, + }, + mode: "onChange", + reValidateMode: "onChange", + resolver: yupResolver(switchExampleSchema), + }); + + return ( +
+ + + + ); +}; + export const FormExample = { render: () => { return ( diff --git a/packages/react/src/components/Forms/Switch/index.tsx b/packages/react/src/components/Forms/Switch/index.tsx index 76e3b5a..c417971 100644 --- a/packages/react/src/components/Forms/Switch/index.tsx +++ b/packages/react/src/components/Forms/Switch/index.tsx @@ -1,4 +1,4 @@ -import React, { InputHTMLAttributes } from "react"; +import React, { InputHTMLAttributes, forwardRef } from "react"; import classNames from "classnames"; import { Field, FieldProps } from ":/components/Forms/Field"; @@ -8,36 +8,33 @@ type Props = InputHTMLAttributes & labelSide?: "left" | "right"; }; -export const Switch = ({ - label, - text, - state, - fullWidth, - labelSide = "left", - - ...props -}: Props) => { - return ( -