useElementsOverflow

Render a list of elements and an overflow element.

Usage

useElementsOverflow takes an object with the following options:

  • items: the list of items to display

The hook returns an object with the following properties:

  • containerRef: the ref of the container outside the list, the available width
  • listRef: the ref of the list that contains the items and the overflow items elements
  • listStyle: the style of the list
  • items: the list of elements that can be displayed inside the container
  • overflowItems: the list of elements that can be displayed in the overflow items (usually a +X counter)
import { useElementsOverflow } from "swash/utils/useElementsOverflow";

  const fruits = [
    "Banana",
    "Apple",
    "Orange",
    "Pineapple",
    "Strawberry",
    "Watermelon",
    "Mango",
    "Peach",
    "Grape",
  ];

  export const Example = () => {
    const { items, overflowItems, containerRef, listRef, listStyle } =
      useElementsOverflow({ items: fruits });

    return (
      <div
        ref={containerRef as React.RefObject<HTMLDivElement>}
        className="w-60 overflow-hidden"
      >
        <div
          ref={listRef as React.RefObject<HTMLDivElement>}
          className="flex gap-2"
          style={listStyle}
        >
          {items.map((item, index) => (
            <div key={index}>{item}</div>
          ))}
          {overflowItems.length > 0 && <span>+{overflowItems.length}</span>}
        </div>
      </div>
    );
  };