---
title: "Segment Group · UI SDK — StyleX Blocks"
description: "A segmented control for mutually exclusive views with an inset track and raised active segment."
url: "https://stylexblocks.com/components/ui-sdk/segment-group/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Segment Group

A segmented control for mutually exclusive views with an inset track and raised active segment.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/segment-group.md), [Base UI](https://stylexblocks.com/components/base-ui/segment-group.md)
- Category: Form
- Sizes: xs, sm, md, lg
- Used in blocks: [Canvas Editor](https://stylexblocks.com/block/ui-sdk/canvas-editor.md), [Collapsible Table](https://stylexblocks.com/block/ui-sdk/collapsible-table.md), [Comparison Table](https://stylexblocks.com/block/ui-sdk/comparison-table.md), [Course Detail](https://stylexblocks.com/block/ui-sdk/course-detail.md), [Data Dashboard](https://stylexblocks.com/block/ui-sdk/data-dashboard.md), [Documentation Design](https://stylexblocks.com/block/ui-sdk/documentation-design.md), [Executive Dashboard](https://stylexblocks.com/block/ui-sdk/executive-dashboard.md), [File Explorer](https://stylexblocks.com/block/ui-sdk/file-explorer.md), [Filterable Table](https://stylexblocks.com/block/ui-sdk/filterable-table.md), [Two-Column Form](https://stylexblocks.com/block/ui-sdk/form-two-column.md), [Dialog Wizard](https://stylexblocks.com/block/ui-sdk/form-wizard-dialog.md), [Inline Wizard](https://stylexblocks.com/block/ui-sdk/form-wizard-inline.md), [Vertical Wizard](https://stylexblocks.com/block/ui-sdk/form-wizard-vertical.md), [Funnel & Cohort Dashboard](https://stylexblocks.com/block/ui-sdk/funnel-cohort-dashboard.md), [Grouped Table](https://stylexblocks.com/block/ui-sdk/grouped-table.md), [IDE Workspace](https://stylexblocks.com/block/ui-sdk/ide.md), [Inbox Table](https://stylexblocks.com/block/ui-sdk/inbox-table.md), [Incident Console](https://stylexblocks.com/block/ui-sdk/incident-console.md), [Mixed Gallery](https://stylexblocks.com/block/ui-sdk/mixed-gallery.md), [Page Editor](https://stylexblocks.com/block/ui-sdk/page-editor.md), [Portfolio Dashboard](https://stylexblocks.com/block/ui-sdk/portfolio-dashboard.md), [Product Detail](https://stylexblocks.com/block/ui-sdk/product-detail.md), [Product Gallery](https://stylexblocks.com/block/ui-sdk/product-gallery.md), [Project Status Dashboard](https://stylexblocks.com/block/ui-sdk/project-status-dashboard.md), [Searchable Table](https://stylexblocks.com/block/ui-sdk/searchable-table.md), [Service Monitoring](https://stylexblocks.com/block/ui-sdk/service-monitoring.md), [Settings Dialog](https://stylexblocks.com/block/ui-sdk/settings-dialog.md), [Settings Form](https://stylexblocks.com/block/ui-sdk/settings-form.md), [Settings Panels](https://stylexblocks.com/block/ui-sdk/settings-panels.md), [Simple Table](https://stylexblocks.com/block/ui-sdk/simple-table.md), [Theme Showcase](https://stylexblocks.com/block/ui-sdk/theme-showcase.md), [Tree Table](https://stylexblocks.com/block/ui-sdk/tree-table.md)
- HTML page: https://stylexblocks.com/components/ui-sdk/segment-group/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add segment-group
```

Equivalent: `npx shadcn add @stylexblocks/segment-group`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/segment-group.json

## Usage

```tsx
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";

export function Example() {
  return (
    // UI SDK's SegmentedControl: a radio group whose indicator measures the
    // checked item; Root renders the indicator for you
    <SegmentGroup.Root defaultValue="preview" size="md" aria-label="View mode">
      <SegmentGroup.Item value="preview">Preview</SegmentGroup.Item>
      <SegmentGroup.Item value="code">Code</SegmentGroup.Item>
    </SegmentGroup.Root>
  );
}

// controlled: <SegmentGroup.Root value={view} onValueChange={setView}>
```

## Source

`components/ui/ui-sdk/segment-group.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { useContext } from "react";
import {
  SegmentedControl as UiSdkSegmentedControl,
  SegmentedControlIndicator as UiSdkSegmentedControlIndicator,
  SegmentedControlItem as UiSdkSegmentedControlItem,
} from "@ui-sdk/react/segmented-control";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type SlotRecipeVariants,
} from "#lib/recipe-props.ts";
import { colors } from '@stylexblocks/ui/tokens/colors.stylex.ts'
import { cursor } from '@stylexblocks/ui/tokens/cursor.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { semanticShadows } from '@stylexblocks/ui/semantic-tokens/shadows.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'

const segmentGroupRoot = stylex.create({
  base: {
    borderRadius: 'var(--segment-radius)',
    display: 'inline-flex',
    boxShadow: semanticShadows.inset,
    minWidth: 'max-content',
    textAlign: 'center',
    position: 'relative',
    isolation: 'isolate',
    backgroundColor: semanticColors.bgMuted,
    borderWidth: '1px',
  },
})

const segmentGroupRootSizes = stylex.create({
  xs: {
    '--segment-radius': semanticRadii.control,
    height: sizes.controlXs,
  },
  sm: {
    '--segment-radius': semanticRadii.control,
    height: sizes.controlSm,
  },
  md: {
    '--segment-radius': semanticRadii.control,
    height: sizes.controlMd,
  },
  lg: {
    '--segment-radius': semanticRadii.control,
    height: sizes.controlLg,
  },
})

const segmentGroupItem = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    userSelect: 'none',
    fontSize: fontSizes.sm,
    position: 'relative',
    color: {
      default: semanticColors.fgSubtle,
      ':hover': semanticColors.fg,
      ':is(:checked, [data-checked], [aria-checked="true"], [data-state="checked"])':
        semanticColors.fg,
    },
    cursor: cursor.button,
    borderRadius: 'var(--segment-radius)',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    '::before': {
      content: '""',
      position: 'absolute',
      insetInlineStart: 0,
      insetBlock: 0,
      backgroundColor: semanticColors.border,
      width: '1px',
      transition: 'opacity 0.2s',
    },
  },
})

const segmentGroupItemSizes = stylex.create({
  xs: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    paddingInline: spacing._3,
    gap: spacing._1,
  },
  sm: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    paddingInline: spacing._4,
    gap: spacing._2,
  },
  md: {
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
    paddingInline: spacing._4,
    gap: spacing._2,
  },
  lg: {
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
    paddingInline: spacing._5,
    gap: spacing._3,
  },
})

const segmentGroupIndicator = stylex.create({
  base: {
    position: 'absolute',
    backgroundColor: `light-dark(${semanticColors.bg}, ${semanticColors.bgEmphasized})`,
    width: 'var(--width)',
    height: 'var(--height)',
    top: 'var(--top)',
    left: 'var(--left)',
    zIndex: -1,
    borderRadius: 'var(--segment-radius)',
    boxShadow: '0 0 0 1px var(--sui-colors-border-emphasized)',
    transitionProperty: 'left, top, width, height',
    transitionDuration: durations.moderate,
    transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
  },
})

export type SegmentGroupSize = keyof typeof segmentGroupRootSizes

const segmentGroupRecipe = defineSlotRecipe({
  slots: {
    root: { styles: segmentGroupRoot, sizes: segmentGroupRootSizes },
    item: { styles: segmentGroupItem, sizes: segmentGroupItemSizes },
    indicator: { styles: segmentGroupIndicator },
  },
  defaultVariants: { size: "md" },
});

// UI SDK stamps `data-checked` on the checked item, which the recipe already
// matches. The divider (the item's `::before`) hides on the first item, the
// checked one, and the one right after it — pure CSS here: the indicator is
// the root's first child, and each item is followed by its hidden radio
// input, so the next item is two siblings on.
const chrome = stylex.create({
  hideDivider: {
    ":is([data-slot=segmented-control-indicator] + *, [data-checked], [data-checked] + [data-slot=segmented-control-input] + *)::before":
      { opacity: 0 },
  },
  btnReset: {
    backgroundColor: "transparent",
    borderWidth: 0,
    margin: 0,
    padding: 0,
    color: "inherit",
    fontFamily: "inherit",
    fontSize: "inherit",
  },
  cursorPointer: { cursor: "pointer" },
});

// UI SDK's indicator only measures: it publishes the checked item's box as
// `--segmented-control-indicator-*` and leaves placement to CSS. The recipe
// places it from Ark's `--left`/`--top`/`--width`/`--height`, so feed
// those. The variables are unset until `data-visible`, so hide it before
// then, and skip the transition on the first placement.
const indicatorPlacement = stylex.create({
  base: {
    "--left": "var(--segmented-control-indicator-left)",
    "--top": "var(--segmented-control-indicator-top)",
    "--width": "var(--segmented-control-indicator-width)",
    "--height": "var(--segmented-control-indicator-height)",
    visibility: {
      default: "hidden",
      ":is([data-visible])": "visible",
    },
    transitionProperty: {
      default: "left, top, width, height",
      ':is([data-activation-direction="none"])': "none",
    },
  },
});

const { withProvider, withContext, VariantContext } =
  createSlotRecipeContext(segmentGroupRecipe);

function RootNode({
  value,
  defaultValue,
  onValueChange,
  children,
  ...props
}: Omit<
  React.ComponentProps<typeof UiSdkSegmentedControl>,
  "value" | "defaultValue" | "onValueChange" | "children"
> & {
  children?: React.ReactNode;
  value?: string | null;
  defaultValue?: string | null;
  onValueChange?: (value: string) => void;
}) {
  const v = useContext(VariantContext);
  return (
    <UiSdkSegmentedControl
      {...props}
      value={value}
      defaultValue={defaultValue}
      onValueChange={(next) => {
        if (typeof next === "string") onValueChange?.(next);
      }}
    >
      <UiSdkSegmentedControlIndicator
        {...stylex.props(
          ...resolveSlotStyles(segmentGroupRecipe.slots.indicator, v),
          indicatorPlacement.base,
        )}
      />
      {children}
    </UiSdkSegmentedControl>
  );
}

export type SegmentGroupVariantProps = Partial<SlotRecipeVariants<typeof segmentGroupRecipe>>;

/**
 * Segment Group — UI SDK's SegmentedControl styled by the StyleX slot
 * recipe. `<SegmentGroup.Root size>` resolves the recipe once; every item
 * inherits it through context. Behavior is UI SDK's: a radio group with
 * arrow keys, `data-checked` on the checked item, and an indicator that
 * measures it. Root renders that indicator itself.
 */
export const SegmentGroup = {
  Root: withProvider(RootNode, "root", "SegmentGroupRoot"),
  Item: withContext(
    UiSdkSegmentedControlItem,
    (v) => [
      chrome.btnReset,
      ...resolveSlotStyles(segmentGroupRecipe.slots.item, v),
      chrome.hideDivider,
      chrome.cursorPointer,
    ],
    "SegmentGroupItem",
  ),
};

export type SegmentGroupRootProps = React.ComponentProps<typeof SegmentGroup.Root>;
export type SegmentGroupItemProps = React.ComponentProps<typeof SegmentGroup.Item>;
```
