Skip to main content

For

Used to render elements from a list and optionally show a fallback when the list is empty.

Anatomy

This component is a utility and does not render any DOM elements.

Import

import { For, type ForProps } from '@pluralsight/react'

Usage

Basic

function BasicExample() {
  const items = ['one', 'two', 'three']

  return (
    <For each={items}>
      {(item, index) => (
        <div key={index}>
          {item} ({index})
        </div>
      )}
    </For>
  )
}

Displaying a fallback

To display a fallback when the list is empty, use the fallback prop.

function BasicExample() {
  const data = useMemo(() => ['one', 'two', 'three'], [])
  const [items, setItems] = useState(() => data)

  function handleClear() {
    setItems([])
  }

  function handleReset() {
    setItems((prev) => [...data])
  }

  return (
    <Flex align="center" justify="space-evenly">
      <Flex align="center" justify="center" gap={8}>
        <For
          each={items}
          fallback={<p data-site-override="clearMargin">No items</p>}
        >
          {(item, index) => (
            <div key={index}>
              {item} ({index})
            </div>
          )}
        </For>
      </Flex>

      <Flex align="center" gap={16}>
        <Button sentiment="default" usage="outline" onClick={handleClear}>
          Clear
        </Button>
        <Button onClick={handleReset}>Reset</Button>
      </Flex>
    </Flex>
  )
}

Behavior

There are no behaviors associated with this component.

API

Parameters

export interface ForProps<T, U extends JSX.Element> {
  each: readonly T[]
  fallback?: NonNullable<ReactNode> | null
  children: (item: T, index: number) => U
}
  1. each: A boolean value to determine whether to render the children or the fallback.
  2. fallback: A ReactNode to render when each is falsey.
  3. children: A function that returns a JSX.Element to render for each item in the list via a map callback.

Accessibility

There is no special accessibility considerations for this component.