Skip to content

FloatingList

Provides the ability to create composable children APIs for list components

import {FloatingList, useListItem} from '@floating-ui/react';

This is useful to prevent the need to keep track of a list item’s index for useListNavigation or useTypeahead.

Manually specifying an index poses problems when wrapper tags surround list items, such as with grouping.

An example of a composable children API looks like the following, where <Select> does not receive an array prop but rather children:

<Select>
  <OptionGroup label="Fruits">
    <Option>Apple</Option>
    <Option>Strawberry</Option>
    <Option>Banana</Option>
  </OptionGroup>
  <OptionGroup label="Vegetables">
    <Option>Carrot</Option>
    <Option>Green Peas</Option>
    <Option>Cauliflower</Option>
  </OptionGroup>
</Select>

Examples

Usage

FloatingList

This component is a context provider that receives two props:

  • elementsRefuseListNavigation()’s listRef prop (array of elements).
  • labelsRefuseTypeahead()’s listRef prop (array of strings; optional).
const elementsRef = useRef([]);
const labelsRef = useRef([]);
 
const listNav = useListNavigation(context, {
  listRef: elementsRef,
});
const typeahead = useTypeahead(context, {
  listRef: labelsRef,
});
 
return (
  <FloatingList elementsRef={elementsRef} labelsRef={labelsRef}>
    {/* floating element with list item children */}
  </FloatingList>
);

useListItem()

This Hook is used to register a list item and its index (DOM position) in the FloatingList. It returns two properties:

ref and index.

function Option() {
  const {activeIndex} = useSelectContext();
  const {ref, index} = useListItem();
 
  const isActive = activeIndex === index;
 
  return <div ref={ref} tabIndex={isActive ? 0 : -1} />;
}

The Hook optionally accepts a label prop, which is used to determine the string that can be matched with typeahead:

function Option({label}) {
  const {activeIndex} = useSelectContext();
  const {ref, index} = useListItem({
    label,
  });
 
  // ...
}

The label can be null for disabled items, which will be ignored for typeahead.