diff --git a/govtool/frontend/src/components/organisms/ControlledField/Checkbox.tsx b/govtool/frontend/src/components/organisms/ControlledField/Checkbox.tsx new file mode 100644 index 000000000..1f134c4af --- /dev/null +++ b/govtool/frontend/src/components/organisms/ControlledField/Checkbox.tsx @@ -0,0 +1,39 @@ +import { useCallback } from "react"; +import { Controller, get } from "react-hook-form"; + +import { Field } from "@molecules"; + +import { ControlledCheckboxProps, RenderInputProps } from "./types"; + +export const Checkbox = ({ + control, + name, + errors, + rules, + ...props +}: ControlledCheckboxProps) => { + const errorMessage = get(errors, name)?.message as string; + + const renderInput = useCallback( + ({ field }: RenderInputProps) => ( + field.onChange(newValue)} + value={field.value} + {...props} + /> + ), + [errorMessage, props] + ); + + return ( + + ); +}; diff --git a/govtool/frontend/src/components/organisms/ControlledField/index.tsx b/govtool/frontend/src/components/organisms/ControlledField/index.tsx index f3b8bbd83..1cb8c7d5c 100644 --- a/govtool/frontend/src/components/organisms/ControlledField/index.tsx +++ b/govtool/frontend/src/components/organisms/ControlledField/index.tsx @@ -1,8 +1,10 @@ import React, { PropsWithChildren } from "react"; +import { Checkbox } from "./Checkbox"; import { Input } from "./Input"; type ControlledFieldComposition = React.FC & { + Checkbox: typeof Checkbox; Input: typeof Input; }; @@ -10,6 +12,7 @@ const ControlledField: ControlledFieldComposition = ({ children }) => { return <>{children}; }; +ControlledField.Checkbox = Checkbox; ControlledField.Input = Input; export { ControlledField }; diff --git a/govtool/frontend/src/components/organisms/ControlledField/types.ts b/govtool/frontend/src/components/organisms/ControlledField/types.ts index 9f539b279..2e276688b 100644 --- a/govtool/frontend/src/components/organisms/ControlledField/types.ts +++ b/govtool/frontend/src/components/organisms/ControlledField/types.ts @@ -1,4 +1,4 @@ -import { InputFieldProps } from "@molecules"; +import { CheckboxFieldProps, InputFieldProps } from "@molecules"; import { Control, ControllerRenderProps, @@ -9,9 +9,16 @@ import { } from "react-hook-form"; export type ControlledInputProps = InputFieldProps & { + control: Control; + errors: FieldErrors; name: Path; + rules?: Omit; +}; + +export type ControlledCheckboxProps = CheckboxFieldProps & { control: Control; errors: FieldErrors; + name: Path; rules?: Omit; };