# Polymorphic components

Build semantic interfaces with Zenos components instead of recreating layout and interaction from raw HTML.

Zenos components separate an element's **meaning** from its **presentation**. Start with the
component that owns the layout, typography, surface, or behavior you need, then select the correct
semantic element through `as` or compose behavior through `render`. This keeps product code aligned
with Zenos without reducing the page to anonymous `div` and `span` wrappers.

```tsx
import { Badge, Box, Cluster, Link, Section, Text, VStack } from "@zentara-co/zenos-ui";

function PolymorphicComponentsExample() {
  const practices = [
    ["01", "Use the semantic element", "Choose article, section, nav, or a real list."],
    ["02", "Keep layout declarative", "Let VStack, HStack, Cluster, and Grid own flow."],
    ["03", "Preserve native behavior", "Use Button and Link for actions and navigation."],
  ] as const;

  return (
    <Section
      as="section"
      aria-labelledby="polymorphic-preview-title"
      gap="5"
      padding={{ base: "4", md: "6" }}
      className="w-full max-w-2xl rounded-xl border border-border-default bg-background-neutral-card"
    >
      <Cluster align="start" justify="between" gap="4" wrap={false}>
        <VStack gap="1" className="min-w-0 flex-1">
          <Text as="p" size="s" color="brand" weight="medium">
            Component-first markup
          </Text>
          <Text id="polymorphic-preview-title" as="h2" type="heading" size="h4">
            Build semantics into the layout
          </Text>
          <Text color="subtle">
            Zenos controls presentation while the as prop controls document meaning.
          </Text>
        </VStack>
        <Badge variant="solid" color="brand">
          Recommended
        </Badge>
      </Cluster>

      <VStack as="ol" gap="3" className="m-0 list-none p-0">
        {practices.map(([number, title, description]) => (
          <Box as="li" key={number} elevation="container" className="rounded-lg p-4">
            <Cluster align="start" gap="3" wrap={false}>
              <Box
                as="span"
                className="grid size-8 shrink-0 place-items-center rounded-full bg-background-brand-default type-body-s text-text-contrary"
              >
                {number}
              </Box>
              <VStack gap="1">
                <Text as="h3" type="heading" size="h7">
                  {title}
                </Text>
                <Text size="s" color="subtle">
                  {description}
                </Text>
              </VStack>
            </Cluster>
          </Box>
        ))}
      </VStack>

      <Cluster as="footer" justify="between" gap="3">
        <Text size="s" color="subtle">
          Semantic HTML, without rebuilding the design system.
        </Text>
        <Link href="#choose-the-right-api">Choose an API</Link>
      </Cluster>
    </Section>
  );
}
```

## The mental model

A polymorphic component keeps its Zenos API and styling while changing the element rendered to the
DOM:

```tsx
<Box as="article" elevation="container">
  <Text as="h2" type="heading" size="h4">
    Release notes
  </Text>
</Box>
```

`Box` still owns the surface. `article` supplies document meaning. `Text` still owns typography,
while `h2` supplies the heading level. TypeScript follows the selected element, so `Box as="a"`
accepts `href` and its ref resolves to an anchor.

The goal is not to hide HTML. The goal is to choose HTML semantics through a consistent Zenos
component instead of rebuilding layout, tokens, states, and accessibility for every screen.

## Start with responsibility

Choose the component before choosing the element. Ask what relationship the wrapper owns:

1. **Vertical flow** — use `VStack` when children always run from top to bottom.
2. **Horizontal flow** — use `HStack` when children stay in one row.
3. **Responsive direction** — use `Stack` when the axis itself changes by breakpoint.
4. **Wrapping row** — use `Cluster` for actions, tags, filters, and metadata that may wrap.
5. **Shared tracks** — use `Grid` for rows and columns that must align.
6. **Width and region** — use `Container` for measure and `Section` for a semantic region.
7. **Surface only** — use `Box` when you need an element, elevation, or customization hook but no
   child-layout rule.
8. **Typography** — use `Text`, then select the correct heading, paragraph, label-like, or inline
   element with `as`.

### VStack, HStack, Stack, or Cluster?

| Component | Default relationship                             | Use it for                                                                             | Prefer another component when                                                         |
| --------- | ------------------------------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `VStack`  | Fixed vertical flex flow                         | Forms, card content, page sections, menus, and semantic vertical lists                 | The direction must become horizontal at a breakpoint.                                 |
| `HStack`  | Fixed horizontal flex flow without wrapping      | Compact metadata, icon-label pairs, and controls that must remain together             | Items should wrap when space runs out.                                                |
| `Stack`   | Configurable flex direction; vertical by default | Responsive or application-controlled direction, scrolling, and dimensional constraints | The direction is permanently vertical or horizontal and a named primitive is clearer. |
| `Cluster` | Horizontal flow that wraps by default            | Toolbars, actions, tags, filters, and variable-width groups                            | Items must share grid tracks or must never wrap.                                      |

`VStack` and `HStack` expose intent directly. They also provide axis-specific aliases:
`VStack` accepts `hAlign` and `vAlign`, while `HStack` accepts `hAlign` and `vAlign`. The shared
`align` and `justify` props remain available when flex terminology is more useful.

```tsx
<VStack as="section" gap="6" hAlign="stretch" aria-labelledby="profile-heading">
  <Text id="profile-heading" as="h2" type="heading" size="h4">
    Profile
  </Text>

  <HStack as="footer" gap="2" hAlign="end">
    <Button>Cancel</Button>
    <Button variant="primary">Save profile</Button>
  </HStack>
</VStack>
```

Use `Stack` when direction is genuinely responsive:

```tsx
<Stack direction={{ base: "column", md: "row" }} gap="4" align={{ md: "center" }}>
  <ProjectSummary />
  <ProjectActions />
</Stack>
```

Use `Cluster` instead when a row should wrap naturally rather than switch to a predefined axis:

```tsx
<Cluster as="nav" gap="2" aria-label="Project filters">
  {filters.map((filter) => (
    <Button key={filter.value} size="sm">
      {filter.label}
    </Button>
  ))}
</Cluster>
```

## Choose the right API

Zenos uses two composition APIs for different responsibilities.

### Use `as` for layout and typography

Use `as` when a Zenos primitive owns presentation and you need to select its semantic element.

```tsx
<Section as="section" aria-labelledby="billing-heading" padding="6">
  <Stack as="header" gap="1">
    <Text id="billing-heading" as="h2" type="heading" size="h4">
      Billing
    </Text>
    <Text>Manage invoices and payment methods.</Text>
  </Stack>
</Section>
```

Common polymorphic primitives include `Box`, `Text`, `Section`, `VStack`, `HStack`, `Stack`,
`Cluster`, `Grid`, `GridItem`, `GridSpan`, `Center`, `Container`, `AspectRatio`, and `FormLayout`.
Product-frame parts such as `Layout.Content` and `SideNav` also preserve their semantic defaults
while accepting `as` when the application needs a different element.

### Default elements

Keep the default when it already matches the content. Add `as` only when the document meaning must
change.

| Component     | Default element                                    | Responsibility                                            | Common `as` values                                |
| ------------- | -------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------- |
| `Box`         | `div`                                              | Surface, elevation, and a stable customization boundary   | `article`, `aside`, `a`, `li`, `span`             |
| `Text`        | `p`, or the element implied by its typography role | Type scale, weight, color, alignment, and truncation      | `h1`–`h6`, `span`, `strong`, `code`               |
| `Section`     | `section`                                          | Semantic region with vertical flow and responsive padding | `article`, `aside`, `div`                         |
| `VStack`      | `div`                                              | Fixed vertical flow and vertical rhythm                   | `section`, `header`, `footer`, `ul`, `ol`, `form` |
| `HStack`      | `div`                                              | Fixed horizontal flow that stays together                 | `header`, `footer`, `nav`, `li`                   |
| `Stack`       | `div`                                              | Responsive direction, wrapping, dimensions, and scrolling | Any structural element whose direction can change |
| `Cluster`     | `div`                                              | Wrapping horizontal groups                                | `nav`, `header`, `footer`, `ul`                   |
| `Grid`        | `div`                                              | Responsive shared tracks                                  | `ul`, `ol`, `section`                             |
| `Center`      | `div`                                              | Centering on one or both axes                             | `section`, `main`, `aside`                        |
| `Container`   | `div`                                              | Maximum width and inline gutters                          | `main`, `section`, `article`                      |
| `FormLayout`  | `div`                                              | Responsive field layout                                   | `form`, `fieldset`                                |
| `AspectRatio` | `div`                                              | Stable media geometry                                     | `figure`, `a`                                     |

`Layout.Header`, `Layout.Content`, `Layout.Footer`, and `Layout.Panel` already default to `header`,
`main`, `footer`, and `aside`. Prefer those defaults unless the region has a different role in the
page.

### Custom React components

`as` accepts a React element type, not only an HTML tag. This is useful for router links or
application-owned semantic wrappers:

```tsx
<Box
  as={RouterLink}
  to="/projects/zenos"
  elevation="raised"
  className="rounded-lg p-4 focus-visible:ring-2 focus-visible:ring-ring"
>
  <Text as="span" weight="medium">
    Open Zenos project
  </Text>
</Box>
```

The custom component must forward its ref and merge `className`, native accessibility attributes,
and event handlers onto the final DOM element. If it drops those props, Zenos styling or behavior
will also be dropped.

### Use `render` for behavior composition

Base UI-backed components, including Link, use `render` when behavior or link styling must be applied
to another component without adding a wrapper element.

```tsx
<Popover.Root>
  <Popover.Trigger render={<Button variant="primary" />}>Open filters</Popover.Trigger>
  <Popover.Content>...</Popover.Content>
</Popover.Root>
```

The trigger remains one native button. Popover supplies focus, keyboard, and open-state behavior;
Button supplies the Zenos appearance. Do not nest a Button inside a trigger that already renders a
button, because nested interactive elements are invalid.

The same rule applies to field controls:

```tsx
<Field.Root>
  <Field.Label>Email</Field.Label>
  <Field.Control render={<Input type="email" autoComplete="email" />} />
</Field.Root>
```

Link uses `render` when a router link should keep Link's color, size, underline, and focus ring:

```tsx
<Link render={<RouterLink to="/workspaces/zenos" />}>View workspace</Link>
```

`RouterLink` must forward `className`, event handlers, and its ref to the underlying anchor.

### Use the dedicated component when one exists

Use `Button`, `Link`, `Input`, `Checkbox`, `Table`, and other purpose-built components directly.
They already provide the correct native element, states, tokens, focus treatment, and public API.
Polymorphism is an escape hatch for semantics, not a reason to replace a focused component with a
generic Box.

## Replace common raw patterns

| Instead of rebuilding                   | Start with                                | Why                                                        |
| --------------------------------------- | ----------------------------------------- | ---------------------------------------------------------- |
| `<div className="flex flex-col gap-4">` | `<VStack gap="4">`                        | VStack states that the flow is intentionally vertical.     |
| `<div className="flex items-center">`   | `<HStack align="center">`                 | HStack keeps a compact row together without wrapping.      |
| `<div className="flex flex-wrap">`      | `<Cluster align="center">`                | Cluster owns a row that can wrap as space changes.         |
| `<div className="grid ...">`            | `<Grid columns={...} gap="4">`            | Grid owns tracks and responsive columns.                   |
| `<div className="max-w-... mx-auto">`   | `<Container size="lg">`                   | Container owns measure and gutters.                        |
| `<section className="py-...">`          | `<Section as="section" paddingY="8">`     | Section combines semantic region and token-based spacing.  |
| `<div className="rounded ...">`         | `<Box elevation="container">`             | Box owns a semantic surface and customization hook.        |
| `<h2 className="...">`                  | `<Text as="h2" type="heading" size="h4">` | Heading level and visual scale stay independent.           |
| `<p className="...">`                   | `<Text color="subtle">`                   | Text owns typography and semantic color.                   |
| `<a className="...">`                   | `<Link href="...">`                       | Link preserves navigation, focus, and link styling.        |
| `<button className="...">`              | `<Button type="button">`                  | Button preserves keyboard behavior and interaction states. |

These are starting points, not mechanical replacements. Choose the component by responsibility,
then choose `as` by meaning.

## Lists without anonymous wrappers

Layout primitives can render list elements while keeping spacing out of individual items:

```tsx
<VStack as="ul" gap="3" className="m-0 list-none p-0">
  {projects.map((project) => (
    <Box as="li" key={project.id} elevation="container" className="rounded-lg p-4">
      <Text as="h3" type="heading" size="h6">
        {project.name}
      </Text>
      <Text color="subtle">{project.description}</Text>
    </Box>
  ))}
</VStack>
```

The DOM remains a real list. VStack owns the gap, each Box owns its item surface, and Text owns the
content hierarchy.

## Copy-ready page structure

The same model scales from a small list to a product page. Each component should own one structural
responsibility:

```tsx
<Layout>
  <Layout.Header>
    <Header>...</Header>
  </Layout.Header>

  <Layout.Content>
    <Section as="section" padding={{ base: "4", lg: "8" }}>
      <Container size="xl">
        <VStack gap={{ base: "6", lg: "8" }}>
          <Cluster as="header" align="center" justify="between" gap="4">
            <VStack gap="1">
              <Text as="h1" type="heading" size="h2">
                Projects
              </Text>
              <Text color="subtle">Manage work across your organization.</Text>
            </VStack>
            <Button variant="primary">New project</Button>
          </Cluster>

          <Grid as="ul" columns={{ base: 1, md: 2, xl: 3 }} gap="4" className="list-none p-0">
            {projects.map((project) => (
              <Box as="li" key={project.id} elevation="container">
                <ProjectCard project={project} />
              </Box>
            ))}
          </Grid>
        </VStack>
      </Container>
    </Section>
  </Layout.Content>
</Layout>
```

In this composition, Layout owns the product frame, Section owns the page region, Container owns
the maximum width, VStack owns vertical rhythm, Cluster owns the wrapping heading row, and Grid owns
the repeated tracks. The rendered `section`, `header`, `h1`, `ul`, and `li` retain the document
structure a browser and assistive technology expect.

## Separate semantics from appearance

Do not choose an element because of its browser default style. Choose it for meaning, then express
the visual hierarchy with component props.

```tsx
<Text as="h2" type="heading" size="h4">
  Workspace members
</Text>
```

Here `h2` maintains document structure while `size="h4"` selects the visual scale. Keep heading
levels sequential even when the design calls for a smaller heading.

Likewise, do not add `onClick` to a `Box`, `Stack`, or `Text` to make it interactive. Use a native
interactive component:

```tsx
<Button type="button" onClick={openWorkspace}>
  Open workspace
</Button>

<Link href="/workspaces/zenos">View workspace</Link>
```

If an entire custom surface navigates, `Box as="a"` is valid when you also provide `href`, a visible
focus treatment, and a clear accessible name. Prefer `Link` when the standard inline-link treatment
is sufficient.

## When to use raw HTML

Native HTML is still appropriate when no Zenos component owns the responsibility and adding a
primitive would make the code less clear—for example `time`, `figure`, `figcaption`, `dl`, or
specialized document content. Use the native element rather than forcing an unrelated component to
fit.

The practical rule is:

1. Use a dedicated Zenos component for known controls and patterns.
2. Use a polymorphic layout or Text primitive when Zenos owns the presentation.
3. Use native HTML when it is the clearest semantic element and Zenos adds no useful behavior or
   design contract.

## Best practices

- Choose semantics before styling: landmark, heading, list, link, button, then visual treatment.
- Use `as` only to change the rendered element; do not use it to imitate another component's
  behavior.
- Use `render` when a Base UI part must share one DOM element with a Zenos control.
- Never nest interactive elements such as a button inside another button or an anchor inside an
  anchor.
- Forward native attributes such as `href`, `type`, `aria-labelledby`, `disabled`, and `required`
  to the element that owns them.
- Let one layout parent own the gap between siblings. Avoid mixing Stack gap with child margins for
  the same relationship.
- Keep `className` for application-specific decoration; prefer semantic component props for layout,
  spacing, state, and variants.
- Preserve visible focus, keyboard behavior, and correct heading order after changing `as` or
  composing with `render`.
- Use logical alignment and spacing so the composition continues to work in RTL.

## Related guides

- [Composition Guide](/layout/composition/) explains how layout primitives share structural
  responsibilities.
- [Box](/layout/box/) covers the lowest-level semantic surface.
- [Text](/components/text/) separates typography role, visual scale, and rendered element.
- [Direction](/components/direction/) explains direction-aware application structure.

Source: https://zenos-ui.pages.dev/layout/polymorphic-components/