listbox

mail@pastecode.io avatar
unknown
javascript
3 years ago
2.9 kB
2
Indexable
import { Fragment } from "react";
import { useField, useFormikContext } from "formik";
import { Listbox, Transition } from "@headlessui/react";
import { CheckIcon, ChevronDownIcon } from "@heroicons/react/solid";

export default function ListBox({
  data,
  selected,
  setSelected,
  label,
  ...props
}) {
  const { setFieldValue } = useFormikContext();
  const [field] = useField(props);

  return (
    <Listbox
      as="div"
      {...field}
      {...props}
      value={field.value}
      onChange={(val) => {
        setFieldValue(field.name, val);
        setSelected(val);
      }}
    >
      <div className="relative">
        <Listbox.Label className="label" htmlFor={label}>
          {label}
        </Listbox.Label>
        <Listbox.Button className="relative w-full py-2 pl-3 pr-10 text-left bg-white form-control">
          <span className="block truncate">{selected.option}</span>
          <span className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
            <ChevronDownIcon
              className="w-5 h-5 text-gray-400"
              aria-hidden="true"
            />
          </span>
        </Listbox.Button>
        <Transition
          as={Fragment}
          leave="transition ease-in duration-100"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <Listbox.Options className="absolute z-10 w-full py-1 mt-1 overflow-auto text-base bg-white rounded-md shadow-lg max-h-60 ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
            {data.map((item, index) => (
              <Listbox.Option
                key={index}
                className={({ active }) =>
                  `${active ? "text-indigo-900 bg-indigo-100" : "text-gray-900"}
                              cursor-default select-none relative py-2 pl-10 pr-4`
                }
                value={item}
              >
                {({ selected, active }) => (
                  <>
                    <span
                      className={`${
                        selected ? "font-medium" : "font-normal"
                      } block truncate`}
                    >
                      {item.option}
                    </span>
                    {selected ? (
                      <span
                        className={`${
                          active ? "text-indigo-600" : "text-indigo-600"
                        }
                                    absolute inset-y-0 left-0 flex items-center pl-3`}
                      >
                        <CheckIcon className="w-5 h-5" aria-hidden="true" />
                      </span>
                    ) : null}
                  </>
                )}
              </Listbox.Option>
            ))}
          </Listbox.Options>
        </Transition>
      </div>
    </Listbox>
  );
}