Keypad
React NativeA number pad to use as is or build key by key.
Preview


Install
Source on GitHubIt works in Expo and in bare React Native. New to beUI Native? Set up your app first.
Copies the component and the shared files it needs into src/, adds the theme tokens if they're missing, and installs its libraries. Files you've changed are kept.
Keep the folder layout, since the component imports the shared files by relative path.
1Install the libraries
npx expo install react-native-reanimated react-native-svg react-native-worklets
npm install uniwind tailwindcss2Add the theme tokens
Once per app. Import it from the CSS file Uniwind reads, after Tailwind and Uniwind, and change the values to match your brand.
/* Matches the default beUI palette in ui-components/lib/themes.ts.
Native surface maps to card; muted maps to muted-foreground. */
@layer theme {
:root {
@variant light {
--color-background: oklch(99% 0 0);
--color-surface: oklch(97% 0 0);
--color-foreground: oklch(15% 0 0);
--color-muted: oklch(50% 0 0);
--color-border: oklch(15% 0 0 / 0.06);
--color-border-strong: oklch(15% 0 0 / 0.16);
--color-primary: #0285f7;
--color-on-primary: #ffffff;
--color-destructive: #dc2626;
--color-success: #059669;
--color-warning: #d97706;
}
}
:root {
@variant dark {
--color-background: #151515;
--color-surface: #1c1c1c;
--color-foreground: oklch(96% 0 0);
--color-muted: oklch(62% 0 0);
--color-border: rgb(255 255 255 / 0.05);
--color-border-strong: rgb(255 255 255 / 0.14);
--color-primary: #0285f7;
--color-on-primary: #ffffff;
--color-destructive: #f87171;
--color-success: #34d399;
--color-warning: #fbbf24;
}
}
/* Tailwind's default monospace stack isn't a font React Native can load. */
:root {
@variant ios {
--font-mono: Menlo;
}
}
:root {
@variant android {
--font-mono: monospace;
}
}
}
3Copy the shared files
import { useEffect, useState } from "react";
import { AccessibilityInfo } from "react-native";
import { useReducedMotion } from "react-native-reanimated";
/** Reanimated supplies a synchronous initial value; native events keep it current. */
export function useReducedMotionPreference() {
const initialValue = useReducedMotion();
const [reducedMotion, setReducedMotion] = useState(initialValue);
useEffect(() => {
let active = true;
let receivedEvent = false;
const subscription = AccessibilityInfo.addEventListener(
"reduceMotionChanged",
(value) => {
receivedEvent = true;
setReducedMotion(value);
},
);
void AccessibilityInfo.isReduceMotionEnabled().then((value) => {
if (active && !receivedEvent) setReducedMotion(value);
});
return () => {
active = false;
subscription.remove();
};
}, []);
return reducedMotion;
}
import { Easing, ReduceMotion } from "react-native-reanimated";
// Mirrors beUI's lib/ease.ts so native motion matches the web library.
export const EASE_OUT = Easing.bezier(0.16, 1, 0.3, 1);
export const EASE_IN_OUT = Easing.bezier(0.77, 0, 0.175, 1);
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
stiffness: 500,
damping: 30,
mass: 0.6,
reduceMotion: ReduceMotion.System,
} as const;
/** Content swaps: label and icon slots trading places inside a control. */
export const SPRING_SWAP = {
stiffness: 460,
damping: 30,
mass: 0.55,
reduceMotion: ReduceMotion.System,
} as const;
/** Shared-layout glides: pills, indicators and panels moving between positions. */
export const SPRING_LAYOUT = {
stiffness: 360,
damping: 32,
mass: 0.6,
reduceMotion: ReduceMotion.System,
} as const;
/** Dragged handles and fills; critically damped so values never rebound off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
reduceMotion: ReduceMotion.System,
} as const;
export const motion = {
press: SPRING_PRESS,
swap: SPRING_SWAP,
layout: SPRING_LAYOUT,
glide: SPRING_GLIDE,
exit: { duration: 160, easing: EASE_OUT, reduceMotion: ReduceMotion.System },
fade: { duration: 150, reduceMotion: ReduceMotion.System },
} as const;
4Copy the component
export type { KeypadLayout, KeypadProps } from "./keypad";
export { Keypad } from "./keypad";
export type { KeypadSize, KeypadVariant } from "./keypad-context";
export type { KeypadDeleteProps } from "./keypad-delete";
export { KeypadDelete } from "./keypad-delete";
export type { KeypadInputOptions } from "./keypad-input";
export { applyKeypadKey } from "./keypad-input";
export type { KeypadKeyProps } from "./keypad-key";
export { KeypadKey } from "./keypad-key";
export type { KeypadRowProps } from "./keypad-row";
export { KeypadRow } from "./keypad-row";
export { KeypadSpacer } from "./keypad-spacer";
import { createContext, useContext } from "react";
export type KeypadVariant = "plain" | "circle";
export type KeypadSize = "sm" | "md";
export type KeypadContextValue = {
onKeyPress?: (key: string) => void;
variant: KeypadVariant;
size: KeypadSize;
disabled: boolean;
reduce: boolean;
};
export const KeypadContext = createContext<KeypadContextValue | null>(null);
export function useKeypad() {
const context = useContext(KeypadContext);
if (!context) throw new Error("Keypad parts must be inside <Keypad>.");
return context;
}
/** Each variant's key size: plain keys are rows, circle keys are round. */
export const KEY_SIZES: Record<
KeypadVariant,
Record<KeypadSize, { height: number; label: string; gap: number }>
> = {
plain: {
sm: { height: 48, label: "text-xl", gap: 0 },
md: { height: 56, label: "text-2xl", gap: 0 },
},
circle: {
sm: { height: 64, label: "text-2xl", gap: 20 },
md: { height: 76, label: "text-3xl", gap: 24 },
},
};
import Svg, { Path } from "react-native-svg";
import { useResolveClassNames } from "uniwind";
import { KeypadKey, type KeypadKeyProps } from "./keypad-key";
/** A backspace mark. */
function DeleteGlyph({ size }: { size: number }) {
const { color } = useResolveClassNames("text-foreground");
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Path
d="M9 5h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6-7z"
stroke={color}
strokeWidth={1.8}
strokeLinejoin="round"
/>
<Path
d="m12 9.5 5 5M17 9.5l-5 5"
stroke={color}
strokeWidth={1.8}
strokeLinecap="round"
/>
</Svg>
);
}
export type KeypadDeleteProps = Omit<KeypadKeyProps, "value"> & {
/** Sent to `onKeyPress`. Defaults to "delete". */
value?: string;
/** The glyph's size. Defaults to 26. */
iconSize?: number;
};
/**
* The delete key: a backspace mark that sends "delete". Pass `onLongPress`
* to clear everything when it's held.
*/
export function KeypadDelete({
value = "delete",
iconSize = 26,
accessibilityLabel = "Delete",
children,
...props
}: KeypadDeleteProps) {
return (
<KeypadKey value={value} accessibilityLabel={accessibilityLabel} {...props}>
{children ?? <DeleteGlyph size={iconSize} />}
</KeypadKey>
);
}
export type KeypadInputOptions = {
/** Digits allowed after the decimal point. 0 turns the point off. Defaults to 2. */
decimals?: number;
/** The longest the value can get, point included. Defaults to 12. */
maxLength?: number;
/** The key that removes the last character. Defaults to "delete". */
deleteKey?: string;
/** The key for the decimal point. Defaults to ".". */
decimalKey?: string;
};
/**
* The value after a key press, for amount and number entry. Digits append
* (a lone "0" is replaced), the point appears once ("0." when empty) and
* respects `decimals`, delete removes the last character, and anything past
* `maxLength` is ignored. Unknown keys leave the value as it is.
*/
export function applyKeypadKey(
value: string,
key: string,
{
decimals = 2,
maxLength = 12,
deleteKey = "delete",
decimalKey = ".",
}: KeypadInputOptions = {},
) {
if (key === deleteKey) return value.slice(0, -1);
if (key === decimalKey) {
if (decimals === 0 || value.includes(".") || value.length >= maxLength) {
return value;
}
return value ? `${value}.` : "0.";
}
if (!/^\d$/.test(key) || value.length >= maxLength) return value;
const fraction = value.split(".")[1];
if (fraction !== undefined && fraction.length >= decimals) return value;
return value === "0" ? key : value + key;
}
import type { ReactNode, Ref } from "react";
import {
Pressable,
type PressableProps,
Text,
View,
type ViewInstance,
} from "react-native";
import Animated, {
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated";
import { EASE_OUT, SPRING_PRESS } from "../../styles/motion";
import { KEY_SIZES, useKeypad } from "./keypad-context";
// The backdrop lights at once and lingers a moment after release.
const LIGHT = { duration: 60, easing: EASE_OUT };
const FADE = { duration: 220, easing: EASE_OUT };
const SINK = 0.08;
export type KeypadKeyProps = Omit<PressableProps, "children" | "style"> & {
/** Sent to the keypad's `onKeyPress`, such as "7", "." or "delete". */
value: string;
/** Replaces the default label, such as an icon. */
children?: ReactNode;
/** Small text under the label, such as "ABC" on a phone pad. */
sublabel?: string;
/** Runs instead of the keypad's `onKeyPress`. */
onPress?: () => void;
className?: string;
ref?: Ref<ViewInstance>;
};
/**
* One key. Plain keys light a soft backdrop while held; circle keys sit in
* a ring that sinks a little and brightens. Pressing sends `value` to the
* keypad's `onKeyPress`, or runs the key's own `onPress`.
*/
export function KeypadKey({
value,
children,
sublabel,
onPress,
disabled: keyDisabled,
accessibilityLabel,
className = "",
ref,
...props
}: KeypadKeyProps) {
const {
onKeyPress,
variant,
size,
disabled: padDisabled,
reduce,
} = useKeypad();
const disabled = padDisabled || !!keyDisabled;
const dims = KEY_SIZES[variant][size];
const circle = variant === "circle";
const pressed = useSharedValue(0);
const glow = useAnimatedStyle(() => ({ opacity: pressed.value }));
const sink = useAnimatedStyle(() => ({
transform: [{ scale: 1 - pressed.value * SINK }],
}));
const press = (on: boolean) => {
if (reduce) pressed.value = on ? 1 : 0;
else if (circle) pressed.value = withSpring(on ? 1 : 0, SPRING_PRESS);
else pressed.value = withTiming(on ? 1 : 0, on ? LIGHT : FADE);
};
const label = children ?? (
<>
<Text className={`font-medium text-foreground ${dims.label}`}>
{value}
</Text>
{sublabel ? (
<Text className="text-xs font-medium tracking-widest text-muted">
{sublabel}
</Text>
) : null}
</>
);
return (
<Pressable
{...props}
ref={ref}
disabled={disabled}
onPress={() => (onPress ? onPress() : onKeyPress?.(value))}
onPressIn={(e) => {
press(true);
props.onPressIn?.(e);
}}
onPressOut={(e) => {
press(false);
props.onPressOut?.(e);
}}
accessibilityRole="keyboardkey"
accessibilityLabel={accessibilityLabel ?? value}
accessibilityState={{ disabled }}
style={[
circle ? { width: dims.height } : { flex: 1 },
{ height: dims.height, opacity: disabled ? 0.4 : 1 },
]}
className={`items-center justify-center ${className}`}
>
{circle ? (
<Animated.View
style={[sink, { width: dims.height, height: dims.height }]}
className="items-center justify-center overflow-hidden rounded-full border border-border bg-surface"
>
<Animated.View
style={glow}
className="absolute inset-0 bg-border-strong"
/>
{label}
</Animated.View>
) : (
<View className="absolute inset-x-1.5 inset-y-0.5">
<Animated.View
style={glow}
className="flex-1 rounded-2xl bg-foreground/10"
/>
</View>
)}
{circle ? null : label}
</Pressable>
);
}
import { View, type ViewProps } from "react-native";
import { KEY_SIZES, useKeypad } from "./keypad-context";
export type KeypadRowProps = ViewProps & { className?: string };
/** A row of keys. Plain keys share its width; circle keys sit apart. */
export function KeypadRow({ className = "", style, ...props }: KeypadRowProps) {
const { variant, size } = useKeypad();
const gap = KEY_SIZES[variant][size].gap;
return (
<View
{...props}
style={[{ gap }, style]}
className={`flex-row ${variant === "circle" ? "justify-center" : ""} ${className}`}
/>
);
}
import { View } from "react-native";
import { KEY_SIZES, useKeypad } from "./keypad-context";
/** An empty slot that holds a key's place, such as left of 0 on a pin pad. */
export function KeypadSpacer() {
const { variant, size } = useKeypad();
const { height } = KEY_SIZES[variant][size];
return (
<View
importantForAccessibility="no-hide-descendants"
style={
variant === "circle" ? { width: height, height } : { flex: 1, height }
}
/>
);
}
import { type ReactNode, useMemo } from "react";
import { View, type ViewProps } from "react-native";
import { useReducedMotionPreference } from "../../hooks/use-reduced-motion";
import {
KeypadContext,
type KeypadSize,
type KeypadVariant,
} from "./keypad-context";
import { KeypadDelete } from "./keypad-delete";
import { KeypadKey } from "./keypad-key";
import { KeypadRow } from "./keypad-row";
import { KeypadSpacer } from "./keypad-spacer";
/** Ready-made layouts for when no keys are passed in. */
export type KeypadLayout = "decimal" | "number" | "pin";
const LETTERS = [
"",
"",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ",
];
const DIGITS = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
];
export type KeypadProps = Omit<ViewProps, "children"> & {
/** Gets each key's value, such as "7", "." or "delete". */
onKeyPress?: (key: string) => void;
/** Flat keys with a backdrop that lights, or round passcode keys. Defaults to plain. */
variant?: KeypadVariant;
size?: KeypadSize;
/**
* Used when there are no children: `decimal` ends in a point, 0 and
* delete; `number` leaves the point out; `pin` adds letters under the
* digits. Defaults to `decimal`.
*/
layout?: KeypadLayout;
/** Takes the bottom left slot of a ready-made layout, such as a Face ID key. */
bottomLeft?: ReactNode;
/** Hides delete in a ready-made layout, such as while nothing is typed. */
showDelete?: boolean;
/** Runs when delete is held in a ready-made layout, such as to clear. */
onDeleteLongPress?: () => void;
deleteLabel?: string;
decimalLabel?: string;
disabled?: boolean;
disableAnimation?: boolean;
/** Your own rows of keys, in place of a ready-made layout. */
children?: ReactNode;
className?: string;
};
/**
* A number pad you can use as is or build key by key. It shares its
* variant, size and `onKeyPress` with every `KeypadKey` inside, so custom
* keys look and behave like the rest.
*/
export function Keypad({
onKeyPress,
variant = "plain",
size = "md",
layout = "decimal",
bottomLeft,
showDelete = true,
onDeleteLongPress,
deleteLabel,
decimalLabel = "Decimal point",
disabled = false,
disableAnimation = false,
children,
className = "",
...props
}: KeypadProps) {
const reduce = useReducedMotionPreference() || disableAnimation;
const context = useMemo(
() => ({ onKeyPress, variant, size, disabled, reduce }),
[onKeyPress, variant, size, disabled, reduce],
);
const pin = layout === "pin";
const circle = variant === "circle";
const ready = (
<>
{DIGITS.map((row) => (
<KeypadRow key={row[0]}>
{row.map((d) => (
<KeypadKey
key={d}
value={d}
sublabel={pin ? LETTERS[Number(d)] : undefined}
/>
))}
</KeypadRow>
))}
<KeypadRow>
{bottomLeft ??
(layout === "decimal" ? (
<KeypadKey value="." accessibilityLabel={decimalLabel} />
) : (
<KeypadSpacer />
))}
<KeypadKey value="0" />
{showDelete ? (
<KeypadDelete
accessibilityLabel={deleteLabel}
onLongPress={onDeleteLongPress}
/>
) : (
<KeypadSpacer />
)}
</KeypadRow>
</>
);
return (
<KeypadContext.Provider value={context}>
<View
{...props}
style={[circle ? { gap: size === "sm" ? 12 : 16 } : null, props.style]}
className={className}
>
{children ?? ready}
</View>
</KeypadContext.Provider>
);
}
Documentation
A number pad for amounts, passcodes and anything else you type with digits. Use a ready-made layout as is, or build it key by key: every key inside shares the pad's look and its onKeyPress, so your own keys fit right in.
import { applyKeypadKey, Keypad, KeypadDelete, KeypadKey, KeypadRow } from "./src";
const [amount, setAmount] = useState("");
// Ready-made: digits, then a point, 0 and delete.
<Keypad
onKeyPress={(key) => setAmount((a) => applyKeypadKey(a, key, { decimals: 2 }))}
onDeleteLongPress={() => setAmount("")}
/>
// A passcode pad with letters under the digits.
<Keypad variant="circle" layout="pin" showDelete={code.length > 0} onKeyPress={onKey} />
// Built key by key.
<Keypad onKeyPress={onKey}>
<KeypadRow>
<KeypadKey value="1" />
<KeypadKey value="2" />
<KeypadKey value="3" />
</KeypadRow>
<KeypadRow>
<KeypadKey value="00" accessibilityLabel="Double zero" />
<KeypadKey value="0" />
<KeypadDelete onLongPress={clear} />
</KeypadRow>
</Keypad>Parts
Keypad: the pad.onKeyPress(key)gets each key's value.variantisplain(flat keys, the default) orcircle(round passcode keys), andsizeissmormd. Without children it draws alayout:decimal(a point, 0 and delete in the bottom row),number(no point) orpin(letters under the digits, no point). For those,bottomLefttakes the bottom left slot (a Face ID key, say),showDeletehides delete,onDeleteLongPressruns when delete is held, anddeleteLabelanddecimalLabelname those keys. Alsodisabled,disableAnimationandclassName.KeypadRow: a row of keys. Plain keys share its width; circle keys sit apart, centered.KeypadKey: one key.valuegoes toonKeyPress.childrenreplaces the label (an icon, or a word in your own style),sublabeladds small text under it, andonPressruns instead ofonKeyPress. It takes Pressable's props, such asonLongPressanddisabled.KeypadDelete: a key with a backspace mark that sendsdelete. Change it withvalue,iconSizeorchildren.KeypadSpacer: an empty slot that holds a key's place.applyKeypadKey(value, key, options): the next value for amount entry. Digits append (a lone 0 is replaced), the point appears once (as "0." when empty), delete removes the last character, and nothing goes pastmaxLength(12) or pastdecimals(2) after the point.deleteKeyanddecimalKeyrename the special keys.
Motion
- Plain: a soft rounded backdrop lights in 60 ms when a key goes down and fades over 220 ms after it comes up, so quick taps still show.
- Circle: the key sinks to 92% on beUI's press spring while its fill brightens, and springs back on release.
- With reduced motion, or
disableAnimation, keys light and dim without fading or sinking.
Accessibility
Each key is a keyboard key named by its value, or by accessibilityLabel when the value isn't readable (delete reads "Delete", the point "Decimal point"). Disabled keys report it and dim to 40%. Keys are at least 48 points tall. Announce what's being typed from your own display, as the showcase does with a polite live region.
Copy this directory, hooks/use-reduced-motion.ts, styles/motion.ts, and the semantic tokens in styles/theme.css. The delete mark needs react-native-svg.