---
title: "Clipboard · Base UI — StyleX Blocks"
description: "Copy a value with one click: a read-only field with a joined copy button, or a standalone icon button."
url: "https://stylexblocks.com/components/base-ui/clipboard/"
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/"
---

# Clipboard

Copy a value with one click: a read-only field with a joined copy button, or a standalone icon button.

- Behavior engine: Base UI
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/clipboard.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/clipboard.md)
- Category: Form
- Variants: outline, subtle
- Sizes: xs, sm, md, lg
- HTML page: https://stylexblocks.com/components/base-ui/clipboard/

## Install

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

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

Then add the item as source you own:

```sh
npx stylexblocks add clipboard
```

Equivalent: `npx shadcn add @stylexblocks/clipboard`. Registry item JSON: https://stylexblocks.com/r/base-ui/clipboard.json

## Usage

```tsx
import { Clipboard } from "#components/ui/base-ui/clipboard.tsx";

export function Example() {
  return (
    // Hand-built on useRender: Root owns the value and copied state, and
    // announces successful copies through a polite live region.
    <Clipboard.Root value="https://stylexblocks.dev/r/clipboard.json">
      <Clipboard.Label>Registry URL</Clipboard.Label>
      <Clipboard.Control>
        <Clipboard.Input />
        <Clipboard.Trigger>
          <Clipboard.Indicator copied={<CheckIcon />}>
            <CopyIcon />
          </Clipboard.Indicator>
        </Clipboard.Trigger>
      </Clipboard.Control>
    </Clipboard.Root>
  );
}
```

## Examples

### Icon button

A Trigger on its own is a square icon button. Drop it next to a code snippet; its accessible label switches to “Copied to clipboard” while the copied state lasts.

```tsx
<Clipboard.Root value={command} size="sm">
  <Clipboard.Trigger>
    <Clipboard.Indicator copied={<CheckIcon />}>
      <CopyIcon />
    </Clipboard.Indicator>
  </Clipboard.Trigger>
</Clipboard.Root>
```

## Source

`components/ui/base-ui/clipboard.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";
import { defineSlotRecipe } from "#lib/recipe-props.ts";
import {
  buttonSizes,
  buttonStyles,
  buttonTextStyles,
  buttonVariants,
} from "@stylexblocks/ui/recipes/button.ts";
import { fieldLabel } from "@stylexblocks/ui/slot-recipes/field.ts";
import { accentPalette } from "@stylexblocks/ui/themes/palettes.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
import { textStyles } from '@stylexblocks/ui/text-styles.ts'

const inputStyles = stylex.create({
  base: {
    width: '100%',
    minWidth: 'var(--input-height)',
    outline: 'none',
    position: 'relative',
    appearance: 'none',
    textAlign: 'start',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
    height: 'var(--input-height)',
    '--focus-color': colorPalette.focusRing,
    '--error-color': semanticColors.borderError,
    '--focus-ring-color': {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
    },
    borderColor: {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
    },
  },
})

const inputSizes = stylex.create({
  xs: {
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2,
    '--input-height': sizes.controlXs,
  },
  sm: {
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2_5,
    '--input-height': sizes.controlSm,
  },
  md: {
    borderRadius: semanticRadii.control,
    paddingInline: spacing._3,
    '--input-height': sizes.controlMd,
  },
  lg: {
    borderRadius: semanticRadii.control,
    paddingInline: spacing._4_5,
    '--input-height': sizes.controlLg,
  },
  xl: {
    borderRadius: semanticRadii.control,
    paddingInline: spacing._6,
    '--input-height': sizes.controlXl,
  },
})

const inputVariants = stylex.create({
  outline: {
    backgroundColor: semanticColors.bg,
    borderWidth: '1px',
    borderColor: {
      default: semanticColors.border,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      ':hover': semanticColors.borderEmphasized,
    },
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    focusRingWidth: 0,
  },
  subtle: {
    borderWidth: '1px',
    borderColor: {
      default: 'transparent',
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
    },
    backgroundColor: semanticColors.bgMuted,
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
  },
  flushed: {
    backgroundColor: 'transparent',
    borderBottomWidth: '1px',
    borderBottomColor: semanticColors.border,
    borderRadius: 0,
    paddingInline: 0,
    borderColor: {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      ':focus-visible': 'var(--focus-color)',
    },
    boxShadow: {
      default: null,
      ':focus-visible': '0px 1px 0px 0px var(--focus-color)',
    },
  },
})

const inputTextStyles = {
  xs: textStyles.xs,
  sm: textStyles.sm,
  md: textStyles.sm,
  lg: textStyles.md,
  xl: textStyles.md,
} as const

export type InputSize = keyof typeof inputSizes

export type InputVariant = keyof typeof inputVariants

// Clipboard composes existing looks: the field label, the input recipe for
// the read-only value, and the button recipe for the square copy trigger
// (`outline` pairs with the surface button, `subtle` with the subtle one).
const clipboardChrome = stylex.create({
  root: {
    display: "flex",
    flexDirection: "column",
    alignItems: "flex-start",
    gap: spacing._1_5,
    width: "100%",
  },
  control: {
    display: "flex",
    alignItems: "stretch",
    alignSelf: "stretch",
    width: "100%",
  },
  trigger: {
    paddingInline: 0,
    aspectRatio: "1",
  },
  indicator: {
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    color: {
      default: null,
      ":is([data-copied])": semanticColors.fgSuccess,
    },
  },
});

// Inside a Control the input and trigger join into one field: the input
// keeps its outer (start) corners, the trigger its end corners, and the
// trigger tucks under the input's end border.
const join = stylex.create({
  input: {
    flexGrow: 1,
    flexShrink: 1,
    minWidth: 0,
    width: "auto",
    borderStartEndRadius: 0,
    borderEndEndRadius: 0,
  },
  trigger: {
    height: "auto",
    marginInlineStart: "-1px",
    borderStartStartRadius: 0,
    borderEndStartRadius: 0,
  },
});

const triggerVariants = {
  outline: buttonVariants.surface,
  subtle: buttonVariants.subtle,
  flushed: buttonVariants.ghost,
} as const;

// the input's size scale (no `2xs`), so both slots share one `size` axis
const triggerSizes = {
  xs: buttonSizes.xs,
  sm: buttonSizes.sm,
  md: buttonSizes.md,
  lg: buttonSizes.lg,
  xl: buttonSizes.xl,
} as const;

// defineSlotRecipe validates the shape at compile time: default values must
// exist in the axis maps, and slot keys must be `styles` or a declared axis
const clipboardRecipe = defineSlotRecipe({
  slots: {
    root: { styles: { base: clipboardChrome.root } },
    label: { styles: fieldLabel },
    control: { styles: { base: clipboardChrome.control } },
    input: { styles: inputStyles, sizes: inputSizes, variants: inputVariants },
    trigger: {
      styles: buttonStyles,
      sizes: triggerSizes,
      variants: triggerVariants,
    },
    indicator: { styles: { base: clipboardChrome.indicator } },
  },
  defaultVariants: { variant: "outline", size: "md" },
});

// Screen-reader-only live region announcing a successful copy.
const srOnly = stylex.create({
  base: {
    position: "absolute",
    width: "1px",
    height: "1px",
    padding: 0,
    margin: "-1px",
    overflow: "hidden",
    clip: "rect(0, 0, 0, 0)",
    whiteSpace: "nowrap",
    borderWidth: 0,
  },
});

const { withProvider, withContext } = createSlotRecipeContext(clipboardRecipe);

// Base UI has no clipboard machine; Root carries the value + copied state
// and hands it to the parts through context.
interface ClipboardState {
  value: string;
  copied: boolean;
  copy: () => void;
  setValue: (value: string) => void;
  inputId: string;
  labelId: string;
}

const ClipboardContext = createContext<ClipboardState | null>(null);

function useClipboard() {
  const ctx = useContext(ClipboardContext);
  if (!ctx) throw new Error("Clipboard parts must be rendered inside <Clipboard.Root>");
  return ctx;
}

// Whether a part renders inside Clipboard.Control (drives the join styles).
const InControlContext = createContext(false);

/** `navigator.clipboard` with the textarea + execCommand fallback. */
async function writeText(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    const el = document.createElement("textarea");
    el.value = text;
    el.setAttribute("readonly", "");
    el.style.position = "fixed";
    el.style.opacity = "0";
    document.body.appendChild(el);
    el.select();
    const ok = document.execCommand("copy");
    el.remove();
    return ok;
  }
}

const copiedAttr = (copied: boolean) => (copied ? "" : undefined);

export type ClipboardRootProps = useRender.ComponentProps<"div"> & {
  /** Controlled value to copy. */
  value?: string;
  /** Initial value when uncontrolled. */
  defaultValue?: string;
  onValueChange?: (details: { value: string }) => void;
  /** Called when the copied state flips on or off. */
  onStatusChange?: (details: { copied: boolean }) => void;
  /** How long the copied state lasts, in ms. @default 3000 */
  timeout?: number;
  /** Text announced to screen readers after a copy. */
  copiedLabel?: string;
};

function RootNode({
  render,
  value,
  defaultValue,
  onValueChange,
  onStatusChange,
  timeout = 3000,
  copiedLabel = "Copied to clipboard",
  children,
  ...rest
}: ClipboardRootProps) {
  const [innerValue, setInnerValue] = useState(defaultValue ?? "");
  const current = value ?? innerValue;
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const statusRef = useRef(onStatusChange);
  statusRef.current = onStatusChange;
  const id = useId();

  useEffect(() => () => clearTimeout(timer.current), []);

  const copy = useCallback(() => {
    void writeText(current).then((ok) => {
      if (!ok) return;
      clearTimeout(timer.current);
      setCopied(true);
      statusRef.current?.({ copied: true });
      timer.current = setTimeout(() => {
        setCopied(false);
        statusRef.current?.({ copied: false });
      }, timeout);
    });
  }, [current, timeout]);

  const state = useMemo<ClipboardState>(
    () => ({
      value: current,
      copied,
      copy,
      setValue: (next) => {
        setInnerValue(next);
        onValueChange?.({ value: next });
      },
      inputId: `${id}-input`,
      labelId: `${id}-label`,
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [current, copied, copy, id],
  );

  const element = useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        "data-copied": copiedAttr(copied),
        children: (
          <>
            {children}
            <span role="status" aria-live="polite" {...stylex.props(srOnly.base)}>
              {copied ? copiedLabel : ""}
            </span>
          </>
        ),
      },
      rest,
    ),
  });
  return <ClipboardContext.Provider value={state}>{element}</ClipboardContext.Provider>;
}

function LabelNode(allProps: useRender.ComponentProps<"label">) {
  const { render, ...rest } = allProps;
  const clipboard = useClipboard();
  return useRender({
    defaultTagName: "label",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        id: clipboard.labelId,
        htmlFor: clipboard.inputId,
        "data-copied": copiedAttr(clipboard.copied),
      },
      rest,
    ),
  });
}

function ControlNode(allProps: useRender.ComponentProps<"div">) {
  const { render, ...rest } = allProps;
  const clipboard = useClipboard();
  const element = useRender({
    defaultTagName: "div",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      { "data-part": "control", "data-copied": copiedAttr(clipboard.copied) },
      rest,
    ),
  });
  return <InControlContext.Provider value={true}>{element}</InControlContext.Provider>;
}

function InputNode(allProps: useRender.ComponentProps<"input">) {
  const { render, ...rest } = allProps;
  const clipboard = useClipboard();
  return useRender({
    defaultTagName: "input",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        id: clipboard.inputId,
        value: clipboard.value,
        readOnly: true,
        "data-copied": copiedAttr(clipboard.copied),
        onFocus: (event: React.FocusEvent<HTMLInputElement>) =>
          event.currentTarget.select(),
      },
      rest,
    ),
  });
}

function TriggerNode(allProps: useRender.ComponentProps<"button">) {
  const { render, ...rest } = allProps;
  const clipboard = useClipboard();
  return useRender({
    defaultTagName: "button",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        type: "button" as const,
        "aria-label": clipboard.copied ? "Copied to clipboard" : "Copy to clipboard",
        "data-copied": copiedAttr(clipboard.copied),
        onClick: clipboard.copy,
      },
      rest,
    ),
  });
}

export type ClipboardIndicatorProps = useRender.ComponentProps<"span"> & {
  /** Rendered instead of `children` while copied. */
  copied?: React.ReactNode;
};

function IndicatorNode({ render, copied, children, ...rest }: ClipboardIndicatorProps) {
  const clipboard = useClipboard();
  return useRender({
    defaultTagName: "span",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps(
      {
        "data-part": "indicator",
        "data-copied": copiedAttr(clipboard.copied),
        children: clipboard.copied ? copied : children,
      },
      rest,
    ),
  });
}

function ValueTextNode(allProps: useRender.ComponentProps<"span">) {
  const { render, ...rest } = allProps;
  const clipboard = useClipboard();
  return useRender({
    defaultTagName: "span",
    render: render as useRender.RenderProp,
    state: {},
    props: mergeProps({ children: clipboard.value }, rest),
  });
}

const StyledInput = withContext(
  InputNode,
  (v) => [
    accentPalette,
    inputStyles.base,
    inputTextStyles[v.size],
    inputSizes[v.size],
    inputVariants[v.variant],
  ],
  "ClipboardInput",
);

function Input({ style, ...props }: React.ComponentProps<typeof StyledInput>) {
  const inControl = useContext(InControlContext);
  return <StyledInput {...props} style={[inControl && join.input, style]} />;
}
Input.displayName = "ClipboardInput";

const StyledTrigger = withContext(
  TriggerNode,
  (v) => [
    buttonStyles.base,
    buttonTextStyles[v.size],
    triggerSizes[v.size],
    triggerVariants[v.variant],
    clipboardChrome.trigger,
  ],
  "ClipboardTrigger",
);

function Trigger({ style, ...props }: React.ComponentProps<typeof StyledTrigger>) {
  const inControl = useContext(InControlContext);
  return <StyledTrigger {...props} style={[inControl && join.trigger, style]} />;
}
Trigger.displayName = "ClipboardTrigger";

/**
 * Clipboard — a hand-built copy-to-clipboard control composed through Base
 * UI's `useRender` / `mergeProps`, wearing the input, button, and field
 * label recipes. `copy()` writes the value with `navigator.clipboard` (with
 * an `execCommand` fallback), flips `data-copied` on every part for
 * `timeout` ms, updates the trigger's accessible label, and announces the
 * copy through a polite live region. `<Clipboard.Root value variant size>`
 * resolves the recipes once; parts inherit them through context and compose
 * via `render`. Put Input and Trigger in a Control to join them into one
 * field, or use a Trigger alone as an icon button. Indicator swaps its
 * children for `copied`.
 */
export const Clipboard = {
  Root: withProvider(RootNode, "root", "ClipboardRoot"),
  Label: withContext(LabelNode, "label", "ClipboardLabel"),
  Control: withContext(ControlNode, "control", "ClipboardControl"),
  Input,
  Trigger,
  Indicator: withContext(IndicatorNode, "indicator", "ClipboardIndicator"),
  ValueText: ValueTextNode,
};
```
