Skip to content

Commit

Permalink
add Checkbox controlledField with types
Browse files Browse the repository at this point in the history
  • Loading branch information
Sworzen1 committed Feb 14, 2024
1 parent 89f059e commit 85389d2
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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.Checkbox
checked={!!field.value}
errorMessage={errorMessage}
name={field.name}
onChange={(newValue) => field.onChange(newValue)}
value={field.value}
{...props}
/>
),
[errorMessage, props]
);

return (
<Controller
name={name}
control={control}
rules={rules}
render={renderInput}
/>
);
};
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import React, { PropsWithChildren } from "react";

import { Checkbox } from "./Checkbox";
import { Input } from "./Input";

type ControlledFieldComposition = React.FC<PropsWithChildren> & {
Checkbox: typeof Checkbox;
Input: typeof Input;
};

const ControlledField: ControlledFieldComposition = ({ children }) => {
return <>{children}</>;
};

ControlledField.Checkbox = Checkbox;
ControlledField.Input = Input;

export { ControlledField };
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InputFieldProps } from "@molecules";
import { CheckboxFieldProps, InputFieldProps } from "@molecules";
import {
Control,
ControllerRenderProps,
Expand All @@ -9,9 +9,16 @@ import {
} from "react-hook-form";

export type ControlledInputProps = InputFieldProps & {
control: Control<any>;
errors: FieldErrors<any>;
name: Path<any>;
rules?: Omit<RegisterOptions, "valueAsNumber" | "valueAsDate" | "setValueAs">;
};

export type ControlledCheckboxProps = CheckboxFieldProps & {
control: Control<any>;
errors: FieldErrors<any>;
name: Path<any>;
rules?: Omit<RegisterOptions, "valueAsNumber" | "valueAsDate" | "setValueAs">;
};

Expand Down

0 comments on commit 85389d2

Please sign in to comment.