Skip to content

Instantly share code, notes, and snippets.

@yinkakun
Forked from thejoyfuldev/App.tsx
Created October 27, 2022 05:17
Show Gist options
  • Select an option

  • Save yinkakun/47d1ae9828576f07d5c919420bbd2a8d to your computer and use it in GitHub Desktop.

Select an option

Save yinkakun/47d1ae9828576f07d5c919420bbd2a8d to your computer and use it in GitHub Desktop.

Revisions

  1. @thejoyfuldev thejoyfuldev created this gist Jul 4, 2021.
    27 changes: 27 additions & 0 deletions App.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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>
    );
    }
    37 changes: 37 additions & 0 deletions listbox.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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>
    </>
    );
    };
    5 changes: 5 additions & 0 deletions types.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    export type Person = {
    id: number;
    name: string;
    unavailable: boolean;
    };