react listbox component in typescript

Here's an example of how to create a simple listbox component in TypeScript using React and React Hooks:

index.ts
import React, { useState } from "react";

interface ListBoxItem {
  id: number;
  label: string;
}

interface ListBoxProps {
  items: ListBoxItem[];
  onChange: (selectedItem: ListBoxItem) => void;
}

const ListBox: React.FC<ListBoxProps> = ({ items, onChange }) => {
  const [selectedItem, setSelectedItem] = useState<ListBoxItem>();

  const handleItemClick = (item: ListBoxItem) => {
    setSelectedItem(item);
    onChange(item);
  };

  return (
    <div>
      {items.map((item) => (
        <div
          key={item.id}
          onClick={() => handleItemClick(item)}
          style={{
            backgroundColor:
              selectedItem?.id === item.id ? "lightblue" : "white",
          }}
        >
          {item.label}
        </div>
      ))}
    </div>
  );
};

export default ListBox;
806 chars
40 lines

In this component, we define two interfaces: ListBoxItem, which represents the shape of each item in the listbox, and ListBoxProps, which defines the props for the component, including the items array and the onChange handler function.

The component uses the useState hook to maintain the currently selected item, and the handleItemClick function is called when an item is clicked. This function updates the state selectedItem and calls the onChange handler with the newly selected item.

The return statement renders the listbox component by mapping over the items prop and rendering a <div> for each item. The backgroundColor style property is set based on whether the item is currently selected or not.

With this code, you can easily create a listbox component in TypeScript that works with React and React Hooks.

gistlibby LogSnag