(react) react-hook-form Checkbox example

Our form elements needs to be usable with react-hook-form
This commit is contained in:
Romain Le Cellier
2023-07-26 16:52:49 +02:00
parent e3bf4cadf2
commit d506cab978
3 changed files with 121 additions and 46 deletions

View File

@@ -85,6 +85,15 @@ You can also define `state`, `text` props on the group component
<Story id="components-forms-checkbox--group-success"/> <Story id="components-forms-checkbox--group-success"/>
</Canvas> </Canvas>
## Usage with react-hook-form
You can use this input with [react-hook-form](https://react-hook-form.com/docs)
<Canvas sourceState="shown">
<Story id="components-forms-checkbox--react-hook-form"/>
</Canvas>
### Props ### Props
<ArgTypes of={Checkbox} /> <ArgTypes of={Checkbox} />

View File

@@ -1,6 +1,15 @@
import { Meta, StoryFn } from "@storybook/react";
import React from "react"; import React from "react";
import { yupResolver } from "@hookform/resolvers/yup";
import { Meta, StoryFn } from "@storybook/react";
import { useForm } from "react-hook-form";
import * as Yup from "yup";
import { Checkbox, CheckboxGroup } from ":/components/Forms/Checkbox/index"; import { Checkbox, CheckboxGroup } from ":/components/Forms/Checkbox/index";
import { Button } from ":/components/Button";
import {
getFieldState,
getFieldErrorMessage,
onSubmit,
} from ":/tests/reactHookFormUtils";
export default { export default {
title: "Components/Forms/Checkbox", title: "Components/Forms/Checkbox",
@@ -138,3 +147,46 @@ export const GroupSuccess = () => (
</CheckboxGroup> </CheckboxGroup>
</div> </div>
); );
export const ReactHookForm = () => {
interface CheckboxExampleFormValues {
terms: boolean;
}
const checkboxExampleSchema = Yup.object().shape({
terms: Yup.boolean()
.required()
.oneOf([true], "You have to accept the terms of use"),
});
const { register, handleSubmit, formState } =
useForm<CheckboxExampleFormValues>({
defaultValues: {
terms: false,
},
mode: "onChange",
reValidateMode: "onChange",
resolver: yupResolver(checkboxExampleSchema),
});
return (
<form
style={{
display: "flex",
flexDirection: "column",
gap: "1rem",
width: "400px",
}}
onSubmit={handleSubmit(onSubmit)}
>
<Checkbox
label="I accept the terms of use"
fullWidth
state={getFieldState("terms", formState)}
text={getFieldErrorMessage("terms", formState)}
{...register("terms")}
/>
<Button fullWidth={true}>Log-in</Button>
</form>
);
};

View File

@@ -1,6 +1,7 @@
import React, { import React, {
InputHTMLAttributes, InputHTMLAttributes,
PropsWithChildren, PropsWithChildren,
forwardRef,
useEffect, useEffect,
useRef, useRef,
useState, useState,
@@ -14,55 +15,68 @@ type Props = InputHTMLAttributes<HTMLInputElement> &
label?: string; label?: string;
}; };
export const Checkbox = ({ export const Checkbox = forwardRef<HTMLInputElement, Props>(
indeterminate, (
className = "", {
checked, indeterminate,
label, className = "",
text, checked,
rightText, label,
state, text,
...props rightText,
}: Props) => { state,
const inputRef = useRef<HTMLInputElement>(null); ...props
const [value, setValue] = useState<boolean>(!!checked); }: Props,
ref,
) => {
const inputRef = useRef<HTMLInputElement>();
const [value, setValue] = useState<boolean>(!!checked);
useEffect(() => { useEffect(() => {
setValue(!!checked); setValue(!!checked);
}, [checked]); }, [checked]);
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
inputRef.current.indeterminate = !!indeterminate; inputRef.current.indeterminate = !!indeterminate;
} }
}, [indeterminate]); }, [indeterminate]);
return ( return (
<label <label
className={classNames("c__checkbox", { className={classNames("c__checkbox", {
"c__checkbox--disabled": props.disabled, "c__checkbox--disabled": props.disabled,
})} })}
> >
<Field text={text} rightText={rightText} compact={true} state={state}> <Field text={text} rightText={rightText} compact={true} state={state}>
<div className="c__checkbox__container"> <div className="c__checkbox__container">
<div className="c__checkbox__wrapper"> <div className="c__checkbox__wrapper">
<input <input
type="checkbox" type="checkbox"
className={className} className={className}
onChange={(e) => setValue(e.target.checked)} {...props}
{...props} onChange={(e) => {
checked={value} setValue(e.target.checked);
ref={inputRef} props.onChange?.(e);
/> }}
<Indeterminate /> checked={value}
<Checkmark /> ref={(checkboxRef) => {
if (typeof ref === "function") {
ref(checkboxRef);
}
inputRef.current = checkboxRef || undefined;
}}
/>
<Indeterminate />
<Checkmark />
</div>
{label && <div className="c__checkbox__label">{label}</div>}
</div> </div>
{label && <div className="c__checkbox__label">{label}</div>} </Field>
</div> </label>
</Field> );
</label> },
); );
};
export const CheckboxGroup = ({ export const CheckboxGroup = ({
children, children,