---
title: "Password Input · UI SDK — StyleX Blocks"
description: "Password fields with a show/hide toggle, built on the input styles in every variant and size."
url: "https://stylexblocks.com/components/ui-sdk/password-input/"
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/"
---

# Password Input

Password fields with a show/hide toggle, built on the input styles in every variant and size.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/password-input.md), [Base UI](https://stylexblocks.com/components/base-ui/password-input.md)
- Category: Form
- Variants: outline, subtle, flushed
- Sizes: xs, sm, md, lg, xl
- Used in blocks: [Basic Login](https://stylexblocks.com/block/ui-sdk/basic-login.md), [Login Card](https://stylexblocks.com/block/ui-sdk/login-card.md), [Login Split](https://stylexblocks.com/block/ui-sdk/login-split.md), [Login SSO](https://stylexblocks.com/block/ui-sdk/login-sso.md), [Settings Form](https://stylexblocks.com/block/ui-sdk/settings-form.md)
- HTML page: https://stylexblocks.com/components/ui-sdk/password-input/

## 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 password-input
```

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

## Usage

```tsx
import { PasswordInput } from "#components/ui/ui-sdk/password-input.tsx";

export function Example() {
  return (
    // UI SDK's password input wearing the input recipe, inside a UI SDK Field
    // that wires the label: it swaps the input type, keeps the caret in place
    // on toggle, re-masks on form submit, and marks parts with data-visible /
    // data-capslock. The toggle is a toggle button ("Show password" +
    // aria-pressed); VisibilityTrigger ships the eye icons
    <PasswordInput.Root variant="outline" size="md" autoComplete="current-password">
      <PasswordInput.Label>Password</PasswordInput.Label>
      <PasswordInput.Control>
        <PasswordInput.Input placeholder="Enter your password" />
        <PasswordInput.VisibilityTrigger />
      </PasswordInput.Control>
    </PasswordInput.Root>
  );
}

// value lives on Root: <PasswordInput.Root value={value} onValueChange={(v) => setValue(v)}>
// controlled: <PasswordInput.Root visible={visible} onVisibilityChange={(d) => setVisible(d.visible)}>
// custom icons: <PasswordInput.VisibilityTrigger><PasswordInput.Indicator fallback={<Eye />}><EyeOff /></PasswordInput.Indicator></PasswordInput.VisibilityTrigger>
```

## Examples

### Strength meter

Pair the field with a Meter that scores the password and switches palette by level.

```tsx
import { useState } from "react";
import { PasswordInput } from "#components/ui/ui-sdk/password-input.tsx";
import { Meter } from "#components/ui/ui-sdk/meter.tsx";
import { amberPalette, greenPalette, redPalette } from "@stylexblocks/ui/themes/palettes.ts";

const levels = [
  { label: "Too short", palette: redPalette },
  { label: "Weak", palette: redPalette },
  { label: "Weak", palette: redPalette },
  { label: "Fair", palette: amberPalette },
  { label: "Good", palette: amberPalette },
  { label: "Strong", palette: greenPalette },
  { label: "Very strong", palette: greenPalette },
];

export function Example({ score }: { score: (password: string) => number /* 0–6 */ }) {
  const [password, setPassword] = useState("");
  const points = score(password);
  const level = levels[points];
  return (
    <>
      {/* the value lives on Root in UI SDK */}
      <PasswordInput.Root
        autoComplete="new-password"
        value={password}
        onValueChange={(value) => setPassword(value)}
      >
        <PasswordInput.Label>New password</PasswordInput.Label>
        <PasswordInput.Control>
          <PasswordInput.Input />
          <PasswordInput.VisibilityTrigger />
        </PasswordInput.Control>
      </PasswordInput.Root>
      <Meter.Root
        value={points}
        max={6}
        variant="subtle"
        size="xs"
        shape="full"
        palette={level.palette}
        aria-label="Password strength"
        aria-valuetext={level.label}
      >
        <Meter.Track>
          <Meter.Range />
        </Meter.Track>
      </Meter.Root>
    </>
  );
}
```

### Invalid and disabled

Root flags reach every part: the input turns the error colour, the toggle disables with the field.

```tsx
import { PasswordInput } from "#components/ui/ui-sdk/password-input.tsx";

export function Example() {
  return (
    <>
      <PasswordInput.Root invalid>
        <PasswordInput.Label>Invalid</PasswordInput.Label>
        <PasswordInput.Control>
          <PasswordInput.Input />
          <PasswordInput.VisibilityTrigger />
        </PasswordInput.Control>
      </PasswordInput.Root>
      <PasswordInput.Root disabled>
        <PasswordInput.Label>Disabled</PasswordInput.Label>
        <PasswordInput.Control>
          <PasswordInput.Input />
          <PasswordInput.VisibilityTrigger />
        </PasswordInput.Control>
      </PasswordInput.Root>
    </>
  );
}
```

## Source

`components/ui/ui-sdk/password-input.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useMemo, useState } from "react";
import { Field as UiSdkField, FieldLabel as UiSdkFieldLabel } from "@ui-sdk/react/field";
import {
  PasswordInput as UiSdkPasswordInput,
  PasswordInputControl as UiSdkPasswordInputControl,
  PasswordInputToggle as UiSdkPasswordInputToggle,
} from "@ui-sdk/react/password-input";
import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type SlotRecipeVariants,
  type WithStyleOverrides,
} from "#lib/recipe-props.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.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

// The field reuses the input recipe as-is; this layer only adds the group
// around it: a stacked root, the label, a relative control that sizes the
// end slot, and the ghost visibility toggle pinned inside the input's end.
const group = stylex.create({
  root: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._1_5,
    width: "100%",
  },
  label: {
    fontWeight: fontWeights.medium,
    userSelect: "none",
    opacity: {
      default: null,
      ":is([data-disabled])": 0.5,
    },
  },
  control: {
    position: "relative",
    display: "flex",
    alignItems: "center",
    width: "100%",
  },
  input: {
    // room for the toggle, which is as wide as the input is tall
    paddingInlineEnd: "var(--input-height)",
  },
  trigger: {
    position: "absolute",
    insetBlockStart: 0,
    insetInlineEnd: 0,
    zIndex: 1,
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    width: "var(--input-height)",
    height: "var(--input-height)",
    padding: 0,
    margin: 0,
    borderWidth: 0,
    borderStyle: "none",
    borderRadius: semanticRadii.control,
    backgroundColor: "transparent",
    appearance: "none",
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: {
      default: "pointer",
      ":is(:disabled, [data-disabled])": "not-allowed",
    },
    opacity: {
      default: null,
      ":is(:disabled, [data-disabled])": 0.5,
    },
    outlineStyle: {
      default: null,
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: null,
      ":focus-visible": "2px",
    },
    outlineOffset: {
      default: null,
      ":focus-visible": "-2px",
    },
    outlineColor: {
      default: null,
      ":focus-visible": colorPalette.focusRing,
    },
  },
  indicator: {
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
  },
  icon: {
    width: "var(--password-input-icon-size)",
    height: "var(--password-input-icon-size)",
    flexShrink: 0,
  },
});

const groupSizes = stylex.create({
  xs: { "--input-height": sizes.controlXs, "--password-input-icon-size": sizes._3_5 },
  sm: { "--input-height": sizes.controlSm, "--password-input-icon-size": sizes._4 },
  md: { "--input-height": sizes.controlMd, "--password-input-icon-size": sizes._4 },
  lg: { "--input-height": sizes.controlLg, "--password-input-icon-size": sizes._5 },
  xl: { "--input-height": sizes.controlXl, "--password-input-icon-size": sizes._5 },
});

const passwordInputRecipe = defineSlotRecipe({
  slots: {
    root: { styles: { base: group.root } },
    label: { styles: { base: group.label }, sizes: inputTextStyles },
    control: { styles: { base: group.control }, sizes: groupSizes },
    input: { styles: inputStyles, variants: inputVariants, sizes: inputSizes },
    visibilityTrigger: { styles: { base: group.trigger } },
    indicator: { styles: { base: group.indicator } },
  },
  defaultVariants: { variant: "outline", size: "md" },
});

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

type PasswordInputVariants = SlotRecipeVariants<typeof passwordInputRecipe>;

function EyeIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(group.icon)}>
      <path
        d="M1.5 8S3.8 3.5 8 3.5 14.5 8 14.5 8 12.2 12.5 8 12.5 1.5 8 1.5 8Z"
        stroke="currentColor"
        strokeWidth="1.25"
        strokeLinejoin="round"
      />
      <circle cx="8" cy="8" r="2" stroke="currentColor" strokeWidth="1.25" />
    </svg>
  );
}

function EyeOffIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(group.icon)}>
      <path
        d="M6.6 3.65A6.9 6.9 0 0 1 8 3.5c4.2 0 6.5 4.5 6.5 4.5a11 11 0 0 1-1.7 2.3M4.3 4.9C2.5 6.1 1.5 8 1.5 8s2.3 4.5 6.5 4.5c1.4 0 2.6-.5 3.6-1.2M6.6 6.6a2 2 0 0 0 2.8 2.8M2 2l12 12"
        stroke="currentColor"
        strokeWidth="1.25"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// --- state --------------------------------------------------------------------
// UI SDK's PasswordInput owns the field behavior (type swap, caret kept on
// toggle, hidden again on submit / page hide, caps-lock state). It renders
// the relative box around input + toggle, so it maps to our Control, while
// our Root is a UI SDK Field: that wires the Label to the input and spreads
// `data-invalid` / `data-disabled` / `data-required` over every part. Root
// keeps visibility (controlled or not) and the field flags in context, so
// Control can hand them to PasswordInput and Indicator can read them.

interface PasswordInputContextValue {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  toggleVisible: () => void;
  readOnly: boolean;
  required: boolean;
  disabled: boolean;
  name?: string;
  autoComplete?: string;
  ignorePasswordManagers: boolean;
  value?: string;
  defaultValue?: string;
  onValueChange?: PasswordInputValueChange;
}

type PasswordInputValueChange = React.ComponentProps<typeof UiSdkPasswordInput>["onValueChange"];

const PasswordInputContext = createContext<PasswordInputContextValue | null>(null);

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

interface PasswordInputOwnProps {
  /** Controlled visibility of the password. */
  visible?: boolean;
  /** @default false */
  defaultVisible?: boolean;
  onVisibilityChange?: (details: { visible: boolean }) => void;
  disabled?: boolean;
  invalid?: boolean;
  readOnly?: boolean;
  required?: boolean;
  /** Form field name, forwarded to the input. */
  name?: string;
  /** @default "current-password" */
  autoComplete?: "current-password" | "new-password";
  /** Adds the opt-out attributes common password managers respect. */
  ignorePasswordManagers?: boolean;
  /**
   * The value, for a controlled field. UI SDK keeps the value on the
   * password input itself, so it goes here rather than on `Input`.
   */
  value?: string;
  /** The value it starts with. A form reset returns here. */
  defaultValue?: string;
  /** Called with the new value and `details.reason` ("input-change", "reset", ...). */
  onValueChange?: PasswordInputValueChange;
}

type FieldRootProps = Omit<React.ComponentProps<typeof UiSdkField>, "disabled" | "invalid" | "name">;

function RootNode({
  visible: visibleProp,
  defaultVisible = false,
  onVisibilityChange,
  disabled = false,
  invalid = false,
  readOnly = false,
  required = false,
  name,
  autoComplete = "current-password",
  ignorePasswordManagers = false,
  value,
  defaultValue,
  onValueChange,
  ...rest
}: FieldRootProps & PasswordInputOwnProps) {
  const [innerVisible, setInnerVisible] = useState(defaultVisible);
  const visible = visibleProp ?? innerVisible;
  const ctx = useMemo<PasswordInputContextValue>(() => {
    const setVisible = (next: boolean) => {
      setInnerVisible(next);
      onVisibilityChange?.({ visible: next });
    };
    return {
      visible,
      setVisible,
      toggleVisible: () => setVisible(!visible),
      readOnly,
      required,
      disabled,
      name,
      autoComplete,
      ignorePasswordManagers,
      value,
      defaultValue,
      onValueChange,
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, readOnly, required, disabled, name, autoComplete, ignorePasswordManagers, value, defaultValue, onValueChange]);
  return (
    <PasswordInputContext.Provider value={ctx}>
      <UiSdkField
        disabled={disabled || undefined}
        // `false` would suppress the browser's own validation; leave it out
        invalid={invalid || undefined}
        {...rest}
      />
    </PasswordInputContext.Provider>
  );
}

function ControlNode(
  props: Omit<
    React.ComponentProps<typeof UiSdkPasswordInput>,
    "visible" | "defaultVisible" | "onVisibleChange" | "value" | "defaultValue"
  >,
) {
  const s = usePasswordInput();
  return (
    <UiSdkPasswordInput
      visible={s.visible}
      onVisibleChange={(next) => s.setVisible(next)}
      name={s.name}
      autoComplete={s.autoComplete}
      readOnly={s.readOnly}
      required={s.required}
      value={s.value}
      defaultValue={s.defaultValue}
      onValueChange={(next, details) => s.onValueChange?.(next, details)}
      {...props}
    />
  );
}

const passwordManagerProps = {
  "data-1p-ignore": "",
  "data-lpignore": "true",
  "data-bwignore": "true",
  "data-form-type": "other",
  "data-protonpass-ignore": "true",
};

function InputNode(props: React.ComponentProps<typeof UiSdkPasswordInputControl>) {
  const s = usePasswordInput();
  return (
    <UiSdkPasswordInputControl
      autoCapitalize="off"
      spellCheck={false}
      data-state={s.visible ? "visible" : "hidden"}
      {...(s.ignorePasswordManagers ? passwordManagerProps : {})}
      {...props}
    />
  );
}

// UI SDK's toggle is a toggle button: a constant name ("Show password") with
// `aria-pressed` carrying whether the password is shown.
function VisibilityTriggerNode({
  children,
  ...rest
}: React.ComponentProps<typeof UiSdkPasswordInputToggle>) {
  const s = usePasswordInput();
  return (
    <UiSdkPasswordInputToggle
      aria-label="Show password"
      data-state={s.visible ? "visible" : "hidden"}
      {...rest}
    >
      {children ?? <Indicator />}
    </UiSdkPasswordInputToggle>
  );
}

interface IndicatorState {
  visible: boolean;
}

/**
 * Indicator — renders `children` while the password is visible and
 * `fallback` while it is masked. Defaults: eye-off / eye.
 */
function IndicatorNode({
  render,
  children,
  fallback,
  ...rest
}: PartProps<"span", IndicatorState> & { fallback?: React.ReactNode }) {
  const s = usePasswordInput();
  const state: IndicatorState = { visible: s.visible };
  return renderElement(
    "span",
    mergeProps(
      {
        "aria-hidden": true,
        "data-state": s.visible ? "visible" : "hidden",
        "data-visible": s.visible ? "" : undefined,
        children: s.visible ? (children ?? <EyeOffIcon />) : (fallback ?? <EyeIcon />),
      },
      rest,
    ),
    render,
    state,
  );
}

/**
 * PasswordInput — UI SDK's password input wearing the input recipe, inside
 * a UI SDK Field for the label. `<PasswordInput.Root variant size>` resolves
 * the recipe once and every part inherits it via context. Root owns
 * visibility (`visible`, `defaultVisible`, `onVisibilityChange`) and the
 * field flags, and the value (`value` / `defaultValue` / `onValueChange` go
 * on Root, not Input: UI SDK keeps the value on the password input). UI SDK
 * swaps the input `type`, keeps the caret in place when toggling, re-masks
 * on form submit, and marks every part with `data-visible`, `data-filled`,
 * `data-capslock`. Every part composes via `render`.
 */
export type PasswordInputRootProps = WithStyleOverrides<FieldRootProps> &
  PasswordInputOwnProps &
  Partial<PasswordInputVariants>;

const PasswordInputRoot = withProvider(RootNode, "root", "PasswordInputRoot");

function Root({ palette = accentPalette, ...props }: PasswordInputRootProps) {
  return (
    <PasswordInputRoot
      palette={palette}
      {...(props as React.ComponentProps<typeof PasswordInputRoot>)}
    />
  );
}
Root.displayName = "PasswordInputRoot";

const Indicator = withContext(IndicatorNode, "indicator", "PasswordInputIndicator");

/** Render-prop access to the visibility state, like Ark's `PasswordInput.Context`. */
function Context({
  children,
}: {
  children: (state: { visible: boolean; setVisible: (v: boolean) => void; toggleVisible: () => void }) => React.ReactNode;
}) {
  return <>{children(usePasswordInput())}</>;
}

export const PasswordInput = {
  Root,
  Label: withContext(UiSdkFieldLabel, "label", "PasswordInputLabel"),
  Control: withContext(ControlNode, "control", "PasswordInputControl"),
  Input: withContext(
    InputNode,
    (v) => [
      ...resolveSlotStyles(passwordInputRecipe.slots.input, v),
      inputTextStyles[v.size],
      group.input,
    ],
    "PasswordInputInput",
  ),
  VisibilityTrigger: withContext(
    VisibilityTriggerNode,
    "visibilityTrigger",
    "PasswordInputVisibilityTrigger",
  ),
  Indicator,
  Context,
};
```
