Add bindings for Select component (#502)

This commit is contained in:
Krzysztof Wolski 2023-05-22 19:29:47 +02:00 committed by GitHub
parent 0c8717a1e5
commit b36502df37
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 112 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
"@saleor/react-hook-form-macaw": minor
---
Add Select input component

View file

@ -1,3 +1,4 @@
export * from "./src/components/Input"; export * from "./src/components/Input";
export * from "./src/components/Combobox"; export * from "./src/components/Combobox";
export * from "./src/components/Multiselect"; export * from "./src/components/Multiselect";
export * from "./src/components/Select";

View file

@ -0,0 +1,70 @@
import { useEffect } from "react";
import { Meta, StoryObj } from "@storybook/react";
import { Select } from "./Select";
import { useForm } from "react-hook-form";
import { action } from "@storybook/addon-actions";
const meta: Meta<typeof Select> = {
title: "Components / Select",
component: Select,
};
export default meta;
type Story = StoryObj<typeof Select>;
const SelectTemplate: Story = {
render: (args) => {
const { control, watch, setError } = useForm();
const name = "selectField";
if (args.error) {
setError(name, { message: "Error message" });
}
useEffect(() => {
const subscription = watch((value) => action("[React Hooks Form] Form value changed")(value));
return () => subscription.unsubscribe();
}, [watch]);
return (
<Select
{...args}
control={control}
label="Select field"
name={name}
options={[
{ value: "1", label: "One" },
{ value: "2", label: "Two" },
{ value: "3", label: "Three" },
]}
/>
);
},
};
export const Default: Story = {
...SelectTemplate,
};
export const Errored: Story = {
...SelectTemplate,
args: {
error: true,
},
};
export const Disabled: Story = {
...SelectTemplate,
args: {
disabled: true,
},
};
export const WithHelpText: Story = {
...SelectTemplate,
args: {
helperText: "Helper text",
},
};

View file

@ -0,0 +1,36 @@
import { Select as $Select, type SelectProps as $SelectProps } from "@saleor/macaw-ui/next";
import { Control, Controller, FieldPath, FieldValues } from "react-hook-form";
export type SelectProps<T extends FieldValues = FieldValues> = Omit<$SelectProps, "name"> & {
name: FieldPath<T>;
control: Control<T>;
};
export function Select<TFieldValues extends FieldValues = FieldValues>({
type,
required,
name,
control,
options,
...rest
}: SelectProps<TFieldValues>): JSX.Element {
return (
<Controller
name={name}
control={control}
render={({ field: { value, ...field }, fieldState: { error } }) => (
<$Select
{...rest}
{...field}
options={options}
value={value || ""}
name={name}
required={required}
type={type}
error={!!error}
helperText={rest.helperText}
/>
)}
/>
);
}