Skip to content

Instantly share code, notes, and snippets.

@Mayowa-Ojo
Forked from j-bullard/App.tsx
Last active November 15, 2022 12:59
Show Gist options
  • Save Mayowa-Ojo/8b8acf135294d02389b8257ab8d2598f to your computer and use it in GitHub Desktop.
Save Mayowa-Ojo/8b8acf135294d02389b8257ab8d2598f to your computer and use it in GitHub Desktop.
Headless UI with React Hook Forms
import "./styles.css";
import { Person } from "./types";
import { Listbox } from "./listbox/listbox";
import { useForm } from "react-hook-form";
const people: Person[] = [
{ id: 1, name: "Durward Reynolds", unavailable: false },
{ id: 2, name: "Kenton Towne", unavailable: false },
{ id: 3, name: "Therese Wunsch", unavailable: false },
{ id: 4, name: "Benedict Kessler", unavailable: true },
{ id: 5, name: "Katelyn Rohan", unavailable: false }
];
export default function App() {
const { control } = useForm();
return (
<div className="App">
<Listbox
name="people"
control={control}
rules={{ required: true }}
people={people}
/>
</div>
);
}
import { useController, UseControllerProps } from "react-hook-form";
import { Listbox as ListBox } from "@headlessui/react";
import { Person } from "../types";
type Props = {
people: Person[];
};
export const Listbox = (props: Props & UseControllerProps) => {
const {
field: { value, onChange }
} = useController(props);
const { people } = props;
return (
<>
<ListBox value={value} onChange={onChange}>
<ListBox.Button>
{value ? (value as Person).name : "Select Person"}
</ListBox.Button>
<ListBox.Options>
{people.map((person) => (
<ListBox.Option
key={person.id}
value={person}
disabled={person.unavailable}
>
{person.name}
</ListBox.Option>
))}
</ListBox.Options>
</ListBox>
</>
);
};
export type Person = {
id: number;
name: string;
unavailable: boolean;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment