# React Native Segmented Control

> A React Native segmented control for iOS, Android and the web: a few choices on a track with a sliding thumb, icons on any side, typed values, and sideways scrolling when they don't fit. Zero native code.

# SegmentedControl

`SegmentedControl` picks one of a few options on a track, with the selected one on a sliding thumb. Items share the track's width while they fit, and the track scrolls sideways when they don't. For separate pills, such as filters, use [`ChipGroup`](./chip-group).

```tsx
import { SegmentedControl } from 'patine-ui';
```

```tsx live
import { useState } from 'react';
import { SegmentedControl } from 'patine-ui';

const views = [
  { label: 'Day', value: 'day' },
  { label: 'Week', value: 'week' },
  { label: 'Month', value: 'month' },
];

export default function Example() {
  const [view, setView] = useState('week');
  return <SegmentedControl items={views} value={view} onValueChange={setView} accessibilityLabel="Calendar view" />;
}
```

## Example: a fitness summary

A fitness app's activity card: Week, Month and Year switch the bars and the total, and the control stays the same width whichever is picked.

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { Box, HStack, SegmentedControl, Text, VStack } from 'patine-ui';

const DATA = {
  week: { unit: 'km', labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], values: [5, 0, 8, 6, 0, 12, 4] },
  month: { unit: 'km', labels: ['W1', 'W2', 'W3', 'W4'], values: [31, 24, 38, 35] },
  year: { unit: 'km', labels: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], values: [92, 80, 110, 128, 140, 96, 70, 88, 132, 141, 120, 0] },
};

export default function Example() {
  const [range, setRange] = useState<keyof typeof DATA>('week');
  const { labels, values, unit } = DATA[range];
  const max = Math.max(...values);
  return (
    <Box border radius="lg" padding="md" gap="md" style={{ width: '100%', maxWidth: 400 }}>
      <SegmentedControl
        items={[{ label: 'Week', value: 'week' }, { label: 'Month', value: 'month' }, { label: 'Year', value: 'year' }]}
        value={range}
        onValueChange={setRange}
        accessibilityLabel="Time range"
      />
      <VStack>
        <Text size="3xl" weight="semibold">{values.reduce((a, b) => a + b, 0)} {unit}</Text>
        <Text color="textSecondary">Running, this {range}</Text>
      </VStack>
      <HStack gap="xs" align="flex-end" style={{ height: 120 }} accessibilityLabel={labels.map((l, i) => `${l} ${values[i]} ${unit}`).join(', ')}>
        {values.map((v, i) => (
          <VStack key={i} gap="xs" align="center" style={{ flex: 1 }}>
            <View style={{ width: '70%', height: max ? (v / max) * 96 + 2 : 2, borderRadius: 4, backgroundColor: v ? '#0EA5E9' : '#E5E7EB' }} />
            <Text size="xs" color="textSecondary">{labels[i]}</Text>
          </VStack>
        ))}
      </HStack>
    </Box>
  );
}
```

## Many options

A few items share the track's width. With more than fit, the track scrolls, and the thumb follows the selection along it. In the Material design there's no thumb: the segments are outlined, as in Material's segmented buttons, and the chosen one is filled and shows a ✓ in place of its icon.

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { SegmentedControl } from 'patine-ui';

const sorts = ['Popular', 'Newest', 'Price'].map((s) => ({ label: s, value: s }));
const ranges = ['1D', '1W', '1M', '3M', '6M', 'YTD', '1Y', '2Y', '5Y', '10Y', 'All'].map((r) => ({ label: r, value: r }));

export default function Example() {
  const [sort, setSort] = useState('Popular');
  const [range, setRange] = useState('1M');
  return (
    <View style={{ gap: 16 }}>
      <SegmentedControl items={sorts} value={sort} onValueChange={setSort} accessibilityLabel="Sort by" />
      <SegmentedControl items={ranges} value={range} onValueChange={setRange} accessibilityLabel="Chart range" />
    </View>
  );
}
```

## Icons

Give an item an `icon` and choose its side with `iconPosition`: `'left'` (the default), `'right'`, `'top'` or `'bottom'`. `'left'` and `'right'` follow the layout direction, so they swap in RTL. An icon can also be a function of `{ selected, disabled, color }`, to color it like its label.

```tsx live
import { useState } from 'react';
import { SegmentedControl } from 'patine-ui';
import { Icon } from '@patine-ui/icons';
import type { IconName } from '@patine-ui/icons';

const views = [
  { label: 'List', value: 'list', icon: 'layoutList' },
  { label: 'Grid', value: 'grid', icon: 'layoutGrid3' },
  { label: 'Map', value: 'map', icon: 'map' },
  { label: 'Calendar', value: 'calendar', icon: 'calendar' },
].map((v) => ({
  ...v,
  icon: ({ color }: { color: string }) => <Icon name={v.icon as IconName} color={color} />,
}));

export default function Example() {
  const [view, setView] = useState('grid');
  return <SegmentedControl items={views} value={view} onValueChange={setView} iconPosition="top" accessibilityLabel="Show listings as" />;
}
```

## Any value type

Values can be anything: numbers, ids, objects. `SegmentedControl<T>` infers `T` from `items`, so `onValueChange` gets the typed value.

```tsx live
import { useState } from 'react';
import { Text, View } from 'react-native';
import { SegmentedControl, useTheme } from 'patine-ui';

const bill = 64.5;
const tips = [0, 10, 15, 18, 20, 25, 30].map((percent) => ({ label: percent ? `${percent}%` : 'No tip', value: percent }));

export default function Example() {
  const theme = useTheme();
  const [tip, setTip] = useState(18);
  return (
    <View style={{ gap: 12 }}>
      <SegmentedControl items={tips} value={tip} onValueChange={setTip} accessibilityLabel="Tip" />
      <Text style={{ color: theme.colors.text, fontSize: 16 }}>Total: ${(bill * (1 + tip / 100)).toFixed(2)}</Text>
    </View>
  );
}
```

Object values are compared with `Object.is`. When they're recreated (say, refetched from a server), pass `isEqual`:

```tsx
<SegmentedControl items={plans} value={plan} onValueChange={setPlan} isEqual={(a, b) => a.id === b.id} />
```

## Behaviour

- **Controlled**: pass `value` and update it in `onValueChange`. Tapping the selected item calls `onValueChange` again.
- The thumb slides to the selected item (in Material, the selected segment is filled instead).
- Tapping an item whose neighbor is hidden scrolls that neighbor into view, plus a little of the one after it, so the user sees there's more.
- `showArrows` adds ‹ › buttons, as in [`ChipGroup`](./chip-group#scroll-arrows). The arrows need a frame around the list: `style` lays out that frame and `styles.container` styles the track itself.

## Accessibility

The control is a `radiogroup` named by `accessibilityLabel`; items are `radio`s with `checked` and `disabled` states. Arrow keys move between items on the web.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `ReadonlyArray<ChoiceItem<T>>` | **required** | `{ label, value, disabled?, icon? }`. `icon` is a node, or a function of `{ selected, disabled, color }`. |
| `value` | `T \| null` | — | Selected value. |
| `onValueChange` | `(value: T, item) => void` | — | Called on tap. |
| `iconPosition` | `'left' \| 'right' \| 'top' \| 'bottom'` | `'left'` | Where each icon sits around its label. |
| `showArrows` | `boolean` | `false` | Round ‹ › buttons that scroll about a page, shown while the items overflow. |
| `arrowPosition` | `'outside' \| 'overlay'` | `'outside'` | Beside the list, the one that can't scroll further dimmed; or over its edges, each shown while items hide past it. |
| `renderArrow` | `(side: 'left' \| 'right', disabled: boolean) => ReactNode` | — | Custom arrow content. |
| `isEqual` | `(a: T, b: T) => boolean` | `Object.is` | Value equality. |
| `renderItem` | `(info: { item, selected, disabled, theme }) => ReactNode` | — | Custom item content. |
| `accessibilityLabel` | `string` | — | Names the list for screen readers. |
| `style` | `StyleProp<ViewStyle>` | — | Container style. |
| `styles` | `SlotStyles<ChoiceSlot>` | — | Slots below. |
| `theme` | `DeepPartial<Theme>` | — | Theme override. |
| `design` | `'brand' \| 'ios' \| 'material' \| 'web' \| 'native'` | from `PatineProvider` | The look to follow, over the provider's: [brand, iOS, Material or web](../guides/designs), or `'native'` for the platform's own. |
| `testID` | `string` | — | Test ID; items get `{testID}-item-{index}`, arrows `{testID}-arrow-left` / `{testID}-arrow-right`. |

### Slots

| Slot | Element |
| --- | --- |
| `container` | The scroll view (the track in `segmented`) |
| `content` | The row inside it |
| `item` / `selectedItem` | Each item / the selected one |
| `itemLabel` / `selectedItemLabel` | Item label |
| `thumb` | The sliding thumb (`segmented`, not in Material) |
| `arrow` / `arrowText` | Each scroll arrow / its glyph (`showArrows`) |

## Related

- [`ChipGroup`](./chip-group): the same choice as separate pills
- [Shop filters sheet example](/examples/shop-filters): a segmented sort order inside a sheet
- [Flight search example](/examples/flight-search): trip type in a booking form
- [Migrating from @react-native-segmented-control](../resources/migration/segmented-control)
