All componentsStrength: Strong
Password Input
Password fields with a show/hide toggle, built on the input styles in every variant and size.
12345678910111213141516171819import { PasswordInput } from "#components/ui/base-ui/password-input.tsx";
export function Example() { return ( // hand-built around Base UI's Input (Base UI has no password input): // Root owns visibility, wires the label, swaps the input type and labels // the toggle "Show password" / "Hide password" <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> );}
// controlled: <PasswordInput.Root visible={visible} onVisibilityChange={(d) => setVisible(d.visible)}>// custom icons: <PasswordInput.VisibilityTrigger><PasswordInput.Indicator fallback={<Eye />}><EyeOff /></PasswordInput.Indicator></PasswordInput.VisibilityTrigger>Variants
outline
subtle
flushed
Sizes
xs
sm
md
lg
xl
Strength meter
Pair the field with a Meter that scores the password and switches palette by level.
123456789101112131415161718192021222324252627282930313233343536373839404142434445import { useState } from "react";import { PasswordInput } from "#components/ui/base-ui/password-input.tsx";import { Meter } from "#components/ui/base-ui/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 ( <> <PasswordInput.Root autoComplete="new-password"> <PasswordInput.Label>New password</PasswordInput.Label> <PasswordInput.Control> <PasswordInput.Input value={password} onChange={(e) => setPassword(e.currentTarget.value)} /> <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.
12345678910111213141516171819202122import { PasswordInput } from "#components/ui/base-ui/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> </> );}Install
1npx stylexblocks add password-inputSource
components/ui/base-ui/password-input.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565import * as stylex from "@stylexjs/stylex";import { createContext, useContext, useId, useMemo, useState } from "react";import { Input as BaseInput } from "@base-ui/react/input";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, 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 --------------------------------------------------------------------// Base UI has no password-input primitive. Root owns the visibility state// and the field flags, and shares them (plus the input id the Label and the// toggle point at) with the parts.
interface PasswordInputState { visible: boolean; setVisible: (visible: boolean) => void; toggleVisible: () => void; inputId: string; disabled: boolean; invalid: boolean; readOnly: boolean; required: boolean; name?: string; autoComplete?: string; ignorePasswordManagers: boolean;}
const PasswordInputContext = createContext<PasswordInputState | null>(null);
function usePasswordInput() { const ctx = useContext(PasswordInputContext); if (!ctx) throw new Error("PasswordInput parts must be rendered inside <PasswordInput.Root>"); return ctx;}
const dataAttr = (on: boolean) => (on ? "" : undefined);
function stateAttrs(s: PasswordInputState) { return { "data-disabled": dataAttr(s.disabled), "data-invalid": dataAttr(s.invalid), "data-readonly": dataAttr(s.readOnly), };}
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;}
function RootNode({ render, visible: visibleProp, defaultVisible = false, onVisibilityChange, disabled = false, invalid = false, readOnly = false, required = false, name, autoComplete = "current-password", ignorePasswordManagers = false, ...rest}: useRender.ComponentProps<"div"> & PasswordInputOwnProps) { const [innerVisible, setInnerVisible] = useState(defaultVisible); const visible = visibleProp ?? innerVisible; const inputId = useId(); const state = useMemo<PasswordInputState>(() => { const setVisible = (next: boolean) => { setInnerVisible(next); onVisibilityChange?.({ visible: next }); }; return { visible, setVisible, toggleVisible: () => setVisible(!visible), inputId, disabled, invalid, readOnly, required, name, autoComplete, ignorePasswordManagers, }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [visible, inputId, disabled, invalid, readOnly, required, name, autoComplete, ignorePasswordManagers]); const element = useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps<"div">(stateAttrs(state) as React.ComponentProps<"div">, rest), }); return <PasswordInputContext.Provider value={state}>{element}</PasswordInputContext.Provider>;}
function LabelNode({ render, ...rest }: useRender.ComponentProps<"label">) { const s = usePasswordInput(); return useRender({ defaultTagName: "label", render: render as useRender.RenderProp, props: mergeProps<"label">( { htmlFor: s.inputId, ...stateAttrs(s), "data-required": dataAttr(s.required), } as React.ComponentProps<"label">, rest, ), });}
function ControlNode({ render, ...rest }: useRender.ComponentProps<"div">) { const s = usePasswordInput(); return useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps<"div">(stateAttrs(s) as React.ComponentProps<"div">, rest), });}
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 BaseInput>) { const s = usePasswordInput(); return ( <BaseInput id={s.inputId} name={s.name} type={s.visible ? "text" : "password"} autoComplete={s.autoComplete} autoCapitalize="off" spellCheck={false} disabled={s.disabled} readOnly={s.readOnly} required={s.required} aria-invalid={s.invalid || undefined} data-state={s.visible ? "visible" : "hidden"} {...stateAttrs(s)} {...(s.ignorePasswordManagers ? passwordManagerProps : {})} {...props} /> );}
function VisibilityTriggerNode({ render, children, ...rest }: useRender.ComponentProps<"button">) { const s = usePasswordInput(); const interactive = !s.disabled && !s.readOnly; return useRender({ defaultTagName: "button", render: render as useRender.RenderProp, props: mergeProps<"button">( { type: "button", "aria-controls": s.inputId, "aria-label": s.visible ? "Hide password" : "Show password", disabled: s.disabled, "data-state": s.visible ? "visible" : "hidden", "data-disabled": dataAttr(s.disabled), "data-readonly": dataAttr(s.readOnly), // keep focus (and the caret) in the input while toggling by pointer onMouseDown: (event: React.MouseEvent) => event.preventDefault(), onClick: () => { if (interactive) s.toggleVisible(); }, children: children ?? <Indicator />, } as React.ComponentProps<"button">, rest, ), });}
/** * Indicator — renders `children` while the password is visible and * `fallback` while it is masked. Defaults: eye-off / eye. */function IndicatorNode({ render, children, fallback, ...rest}: useRender.ComponentProps<"span"> & { fallback?: React.ReactNode }) { const s = usePasswordInput(); return useRender({ defaultTagName: "span", render: render as useRender.RenderProp, props: mergeProps<"span">( { "aria-hidden": true, "data-state": s.visible ? "visible" : "hidden", ...stateAttrs(s), children: s.visible ? (children ?? <EyeOffIcon />) : (fallback ?? <EyeIcon />), } as React.ComponentProps<"span">, rest, ), });}
/** * PasswordInput — a hand-built password field for Base UI (which ships no * password-input primitive): Base UI's `Input` plus a visibility toggle, * composed through `useRender` / `mergeProps` and wearing the input recipe. * `<PasswordInput.Root variant size>` resolves the recipe once and every * part inherits it via context. Root owns visibility (`visible`, * `defaultVisible`, `onVisibilityChange`), wires the Label to the Input, * swaps the input `type`, and labels the toggle "Show password" / "Hide * password". Every part composes via `render`. */export type PasswordInputRootProps = WithStyleOverrides<useRender.ComponentProps<"div">> & 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(LabelNode, "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,};