Control · Inputs
Text field
Screen
Colour scheme
Mode
Corners
Colours
Every state
- When
- Behaviour
Save these 2 files in components/mobilens/. They need only react-native (checked with Expo SDK 58).
// Text field: a label above, help or an error below, a character count, a clear button, and Show / Hide for passwords.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useImperativeHandle, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type TextFieldVariant = 'outlined' | 'underlined' | 'filled';
export type TextFieldProps = {
/** Shown above the field and announced by screen readers. */
label: string;
/** The text. Keep it in state and pass it back. */
value: string;
/** Called with the new text on every edit. */
onChangeText: (value: string) => void;
/** Draw an outline, a bottom line, or a tinted box around the input. */
variant?: TextFieldVariant;
/** Minimum height of the whole labelled field. Additional space is given to the input. */
minHeight?: number;
/** Grey hint inside the empty field. Not a replacement for the label. */
placeholder?: string;
/** One line of help under the field. Hidden while there is an error. */
helper?: string;
/** The error message. The field turns red while it is set; clear it when the user edits. */
error?: string;
/** Grey and read-only. */
disabled?: boolean;
/** The most characters allowed. Shows a count under the field. */
maxLength?: number;
/** Hides the text and adds a Show / Hide button. */
secureTextEntry?: boolean;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'>;
/** The TextInput, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function TextField({
label, value, onChangeText, variant = 'outlined', minHeight, placeholder, helper, error, disabled = false, maxLength, secureTextEntry = false, autoFocus = false, inputProps, ref, copyTestIDs,
}: TextFieldProps & Pick<FieldFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
const [shown, setShown] = useState(false);
const input = useRef<ComponentRef<typeof TextInput>>(null);
useImperativeHandle(ref, () => input.current!, []);
const trailing = secureTextEntry ? (
<Pressable onPress={() => setShown((s) => !s)} hitSlop={8} accessibilityRole="button" accessibilityLabel={shown ? 'Hide password' : 'Show password'} disabled={disabled}>
<Text style={styles.action}>{shown ? 'Hide' : 'Show'}</Text>
</Pressable>
) : value && !disabled ? (
<Pressable onPress={() => { onChangeText(''); input.current?.focus(); }} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Clear ${label}`}>
<View style={styles.clear}><Text style={styles.clearMark}>×</Text></View>
</Pressable>
) : null;
return (
<FieldFrame label={label} copyTestIDs={copyTestIDs} variant={variant} minHeight={minHeight} helper={helper} error={error} disabled={disabled} focused={focused} count={maxLength ? [value.length, maxLength] : undefined} trailing={trailing}>
<TextInput
underlineColorAndroid="transparent"
{...inputProps}
ref={input}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.outline}
editable={!disabled}
maxLength={maxLength}
secureTextEntry={secureTextEntry && !shown}
autoFocus={autoFocus}
onFocus={(e) => {
setFocused(true);
inputProps?.onFocus?.(e);
}}
onBlur={(e) => {
setFocused(false);
inputProps?.onBlur?.(e);
}}
accessibilityLabel={label}
accessibilityHint={error ?? helper}
style={[styles.input, NO_WEB_RING, disabled && styles.inputDisabled]}
/>
</FieldFrame>
);
}
export type FieldFrameProps = {
label: string;
copyTestIDs?: { label?: string; helper?: string };
variant?: TextFieldVariant;
minHeight?: number;
helper?: string;
error?: string;
disabled?: boolean;
focused?: boolean;
count?: [number, number];
trailing?: ReactNode;
children: ReactNode;
};
/** The label, box, help line and count around any input. TextField draws this; use it alone to show a state. */
export function FieldFrame({ label, copyTestIDs, variant = 'outlined', minHeight, helper, error, disabled = false, focused = false, count, trailing, children }: FieldFrameProps) {
const full = !!count && count[0] >= count[1];
const underlined = variant === 'underlined';
const active = !disabled && (focused || !!error);
return (
<View style={[styles.root, minHeight !== undefined && { minHeight }]}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
<View style={[
styles.box, styles[variant], minHeight !== undefined && styles.grow,
active && (underlined ? styles.lineActive : styles.boxActive),
active && { borderColor: error ? colors.error : colors.primary },
disabled && (underlined ? styles.lineDisabled : styles.boxDisabled),
]}>
<View style={styles.inputWrap}>{children}</View>
{trailing}
</View>
{error || helper || count ? (
<View style={styles.below}>
<Text testID={error == null && helper ? copyTestIDs?.helper : undefined} style={[styles.help, !!error && styles.error]} accessibilityLiveRegion={error ? 'polite' : 'none'}>{error ?? helper ?? ''}</Text>
{count ? <Text style={[styles.help, styles.count, full && styles.countFull]}>{count[0]}/{count[1]}</Text> : null}
</View>
) : null}
</View>
);
}
// The box shows focus, so the browser's own focus ring is turned off on the web. React Native's types have no
// 'none' for outlineStyle, but react-native-web passes it through to CSS.
const NO_WEB_RING = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : null;
const styles = StyleSheet.create({
root: { gap: 6 },
grow: { flexGrow: 1 },
label: { fontSize: 14, fontWeight: '500', color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
box: {
minHeight: 50,
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
outlined: {
paddingHorizontal: 14,
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
underlined: { borderBottomWidth: 1, borderColor: colors.outline, paddingTop: 1 },
filled: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: 'transparent', backgroundColor: colors.surfaceVariant },
boxActive: { borderWidth: 2, paddingHorizontal: 13 },
lineActive: { borderBottomWidth: 2, paddingTop: 2 },
lineDisabled: { borderColor: colors.outlineVariant },
boxDisabled: { borderWidth: 0, paddingHorizontal: 15, backgroundColor: colors.surfaceVariant },
inputWrap: { flex: 1, justifyContent: 'center' },
input: { fontSize: 17, color: colors.onSurface, paddingVertical: 12 },
inputDisabled: { color: colors.onSurfaceVariant },
action: { fontSize: 15, fontWeight: '600', color: colors.primary },
clear: { width: 20, height: 20, borderRadius: 10, backgroundColor: colors.outline, alignItems: 'center', justifyContent: 'center' },
clearMark: { marginTop: -2, fontSize: 16, lineHeight: 18, fontWeight: '700', color: colors.surface },
below: { flexDirection: 'row', gap: 12 },
help: { flex: 1, fontSize: 13, color: colors.onSurfaceVariant },
error: { color: colors.error },
count: { flex: 0, fontVariant: ['tabular-nums'] },
countFull: { color: colors.onSurface, fontWeight: '600' },
});
// Text field: a label above, help or an error below, a character count, a clear button, and Show / Hide for passwords.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useImperativeHandle, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react';
import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type TextStyle } from 'react-native';
import { colors, radius } from './theme';
export type TextFieldVariant = 'outlined' | 'underlined' | 'filled';
export type TextFieldProps = {
/** Shown above the field and announced by screen readers. */
label: string;
/** The text. Keep it in state and pass it back. */
value: string;
/** Called with the new text on every edit. */
onChangeText: (value: string) => void;
/** Draw an outline, a bottom line, or a tinted box around the input. */
variant?: TextFieldVariant;
/** Minimum height of the whole labelled field. Additional space is given to the input. */
minHeight?: number;
/** Grey hint inside the empty field. Not a replacement for the label. */
placeholder?: string;
/** One line of help under the field. Hidden while there is an error. */
helper?: string;
/** The error message. The field turns red while it is set; clear it when the user edits. */
error?: string;
/** Grey and read-only. */
disabled?: boolean;
/** The most characters allowed. Shows a count under the field. */
maxLength?: number;
/** Hides the text and adds a Show / Hide button. */
secureTextEntry?: boolean;
/** Focus the field and bring up the keyboard when the screen opens. */
autoFocus?: boolean;
/** Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… */
inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'>;
/** The TextInput, to focus() or blur() it. */
ref?: Ref<ComponentRef<typeof TextInput>>;
};
export function TextField({
label, value, onChangeText, variant = 'outlined', minHeight, placeholder, helper, error, disabled = false, maxLength, secureTextEntry = false, autoFocus = false, inputProps, ref, copyTestIDs,
}: TextFieldProps & Pick<FieldFrameProps, 'copyTestIDs'>) {
const [focused, setFocused] = useState(false);
const [shown, setShown] = useState(false);
const input = useRef<ComponentRef<typeof TextInput>>(null);
useImperativeHandle(ref, () => input.current!, []);
const trailing = secureTextEntry ? (
<Pressable onPress={() => setShown((s) => !s)} hitSlop={8} accessibilityRole="button" accessibilityLabel={shown ? 'Hide password' : 'Show password'} disabled={disabled}>
<Text style={styles.action}>{shown ? 'Hide' : 'Show'}</Text>
</Pressable>
) : value && !disabled ? (
<Pressable onPress={() => { onChangeText(''); input.current?.focus(); }} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Clear ${label}`}>
<View style={styles.clear}><Text style={styles.clearMark}>×</Text></View>
</Pressable>
) : null;
return (
<FieldFrame label={label} copyTestIDs={copyTestIDs} variant={variant} minHeight={minHeight} helper={helper} error={error} disabled={disabled} focused={focused} count={maxLength ? [value.length, maxLength] : undefined} trailing={trailing}>
<TextInput
underlineColorAndroid="transparent"
{...inputProps}
ref={input}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.outline}
editable={!disabled}
maxLength={maxLength}
secureTextEntry={secureTextEntry && !shown}
autoFocus={autoFocus}
onFocus={(e) => {
setFocused(true);
inputProps?.onFocus?.(e);
}}
onBlur={(e) => {
setFocused(false);
inputProps?.onBlur?.(e);
}}
accessibilityLabel={label}
accessibilityHint={error ?? helper}
style={[styles.input, NO_WEB_RING, disabled && styles.inputDisabled]}
/>
</FieldFrame>
);
}
export type FieldFrameProps = {
label: string;
copyTestIDs?: { label?: string; helper?: string };
variant?: TextFieldVariant;
minHeight?: number;
helper?: string;
error?: string;
disabled?: boolean;
focused?: boolean;
count?: [number, number];
trailing?: ReactNode;
children: ReactNode;
};
/** The label, box, help line and count around any input. TextField draws this; use it alone to show a state. */
export function FieldFrame({ label, copyTestIDs, variant = 'outlined', minHeight, helper, error, disabled = false, focused = false, count, trailing, children }: FieldFrameProps) {
const full = !!count && count[0] >= count[1];
const underlined = variant === 'underlined';
const active = !disabled && (focused || !!error);
return (
<View style={[styles.root, minHeight !== undefined && { minHeight }]}>
<Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text>
<View style={[
styles.box, styles[variant], minHeight !== undefined && styles.grow,
active && (underlined ? styles.lineActive : styles.boxActive),
active && { borderColor: error ? colors.error : colors.primary },
disabled && (underlined ? styles.lineDisabled : styles.boxDisabled),
]}>
<View style={styles.inputWrap}>{children}</View>
{trailing}
</View>
{error || helper || count ? (
<View style={styles.below}>
<Text testID={error == null && helper ? copyTestIDs?.helper : undefined} style={[styles.help, !!error && styles.error]} accessibilityLiveRegion={error ? 'polite' : 'none'}>{error ?? helper ?? ''}</Text>
{count ? <Text style={[styles.help, styles.count, full && styles.countFull]}>{count[0]}/{count[1]}</Text> : null}
</View>
) : null}
</View>
);
}
// The box shows focus, so the browser's own focus ring is turned off on the web. React Native's types have no
// 'none' for outlineStyle, but react-native-web passes it through to CSS.
const NO_WEB_RING = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : null;
const styles = StyleSheet.create({
root: { gap: 6 },
grow: { flexGrow: 1 },
label: { fontSize: 14, fontWeight: '500', color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
box: {
minHeight: 50,
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
outlined: {
paddingHorizontal: 14,
borderRadius: radius.md,
borderWidth: 1,
borderColor: colors.outline,
backgroundColor: colors.surface,
},
underlined: { borderBottomWidth: 1, borderColor: colors.outline, paddingTop: 1 },
filled: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: 'transparent', backgroundColor: colors.surfaceVariant },
boxActive: { borderWidth: 2, paddingHorizontal: 13 },
lineActive: { borderBottomWidth: 2, paddingTop: 2 },
lineDisabled: { borderColor: colors.outlineVariant },
boxDisabled: { borderWidth: 0, paddingHorizontal: 15, backgroundColor: colors.surfaceVariant },
inputWrap: { flex: 1, justifyContent: 'center' },
input: { fontSize: 17, color: colors.onSurface, paddingVertical: 12 },
inputDisabled: { color: colors.onSurfaceVariant },
action: { fontSize: 15, fontWeight: '600', color: colors.primary },
clear: { width: 20, height: 20, borderRadius: 10, backgroundColor: colors.outline, alignItems: 'center', justifyContent: 'center' },
clearMark: { marginTop: -2, fontSize: 16, lineHeight: 18, fontWeight: '700', color: colors.surface },
below: { flexDirection: 'row', gap: 12 },
help: { flex: 1, fontSize: 13, color: colors.onSurfaceVariant },
error: { color: colors.error },
count: { flex: 0, fontVariant: ['tabular-nums'] },
countFull: { color: colors.onSurface, fontWeight: '600' },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
Usage
import { useState } from 'react';
import { TextField } from '@/components/mobilens/TextField';
export function EmailField({ onSubmit }: { onSubmit: (email: string) => void }) {
const [email, setEmail] = useState('');
const [error, setError] = useState<string>();
const check = () => {
const ok = /^\S+@\S+\.\S+$/.test(email);
setError(ok ? undefined : 'Enter an email like name@example.com');
return ok;
};
return (
<TextField
variant="outlined"
label="Email"
value={email}
onChangeText={(next) => {
setEmail(next);
setError(undefined);
}}
error={error}
placeholder="name@example.com"
inputProps={{
keyboardType: 'email-address',
autoCapitalize: 'none',
autoCorrect: false,
autoComplete: 'email',
textContentType: 'emailAddress',
returnKeyType: 'next',
onSubmitEditing: () => check() && onSubmit(email),
}}
/>
);
}
import { useState } from 'react';
import { TextField } from '@/components/mobilens/TextField';
export function EmailField({ onSubmit }: { onSubmit: (email: string) => void }) {
const [email, setEmail] = useState('');
const [error, setError] = useState<string>();
const check = () => {
const ok = /^\S+@\S+\.\S+$/.test(email);
setError(ok ? undefined : 'Enter an email like name@example.com');
return ok;
};
return (
<TextField
variant="outlined"
label="Email"
value={email}
onChangeText={(next) => {
setEmail(next);
setError(undefined);
}}
error={error}
placeholder="name@example.com"
inputProps={{
keyboardType: 'email-address',
autoCapitalize: 'none',
autoCorrect: false,
autoComplete: 'email',
textContentType: 'emailAddress',
returnKeyType: 'next',
onSubmitEditing: () => check() && onSubmit(email),
}}
/>
);
}
API
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | – | Shown above the field and announced by screen readers. |
| value | string | – | The text. Keep it in state and pass it back. |
| onChangeText | (value: string) => void | – | Called with the new text on every edit. |
| variant? | TextFieldVariant | 'outlined' | Draw an outline, a bottom line, or a tinted box around the input. |
| minHeight? | number | – | Minimum height of the whole labelled field. Additional space is given to the input. |
| placeholder? | string | – | Grey hint inside the empty field. Not a replacement for the label. |
| helper? | string | – | One line of help under the field. Hidden while there is an error. |
| error? | string | – | The error message. The field turns red while it is set; clear it when the user edits. |
| disabled? | boolean | false | Grey and read-only. |
| maxLength? | number | – | The most characters allowed. Shows a count under the field. |
| secureTextEntry? | boolean | false | Hides the text and adds a Show / Hide button. |
| autoFocus? | boolean | false | Focus the field and bring up the keyboard when the screen opens. |
| inputProps? | Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'> | – | Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… |
| ref? | Ref<ComponentRef<typeof TextInput>> | – | The TextInput, to focus() or blur() it. |
Used in
Add the "Text field" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them. FILES Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths. --- components/mobilens/theme.ts --- // Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app. export const colors = { background: '#fafafa', surface: '#ffffff', surfaceVariant: '#f4f4f5', onBackground: '#18181b', onSurface: '#18181b', onSurfaceVariant: '#6b6b74', outline: '#8a8a93', outlineVariant: '#e4e4e7', error: '#ba1a1a', success: '#296b2a', warning: '#b45309', shadow: '#000000', scrim: 'rgba(0,0,0,0.32)', primary: '#006c50', onPrimary: '#ffffff', primaryContainer: '#82f8cb', onPrimaryContainer: '#002116', secondary: '#3e6374', onSecondary: '#ffffff', secondaryContainer: '#d8dfe2', onSecondaryContainer: '#1c2d34', tertiary: '#1f6862', onTertiary: '#ffffff', tertiaryContainer: '#d3e0df', onTertiaryContainer: '#0e2f2c', onError: '#ffffff', onSuccess: '#ffffff', onWarning: '#ffffff', } as const; export const radius = { sm: 6, md: 12, lg: 20, } as const; --- end of theme.ts --- --- components/mobilens/TextField.tsx --- // Text field: a label above, help or an error below, a character count, a clear button, and Show / Hide for passwords. // Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme. import { useImperativeHandle, useRef, useState, type ComponentRef, type ReactNode, type Ref } from 'react'; import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type TextStyle } from 'react-native'; import { colors, radius } from './theme'; export type TextFieldVariant = 'outlined' | 'underlined' | 'filled'; export type TextFieldProps = { /** Shown above the field and announced by screen readers. */ label: string; /** The text. Keep it in state and pass it back. */ value: string; /** Called with the new text on every edit. */ onChangeText: (value: string) => void; /** Draw an outline, a bottom line, or a tinted box around the input. */ variant?: TextFieldVariant; /** Minimum height of the whole labelled field. Additional space is given to the input. */ minHeight?: number; /** Grey hint inside the empty field. Not a replacement for the label. */ placeholder?: string; /** One line of help under the field. Hidden while there is an error. */ helper?: string; /** The error message. The field turns red while it is set; clear it when the user edits. */ error?: string; /** Grey and read-only. */ disabled?: boolean; /** The most characters allowed. Shows a count under the field. */ maxLength?: number; /** Hides the text and adds a Show / Hide button. */ secureTextEntry?: boolean; /** Focus the field and bring up the keyboard when the screen opens. */ autoFocus?: boolean; /** Keyboard, autofill and return key settings, passed to the TextInput: keyboardType, autoComplete, returnKeyType… */ inputProps?: Omit<TextInputProps, 'value' | 'onChangeText' | 'editable' | 'maxLength' | 'secureTextEntry' | 'autoFocus' | 'placeholder'>; /** The TextInput, to focus() or blur() it. */ ref?: Ref<ComponentRef<typeof TextInput>>; }; export function TextField({ label, value, onChangeText, variant = 'outlined', minHeight, placeholder, helper, error, disabled = false, maxLength, secureTextEntry = false, autoFocus = false, inputProps, ref, copyTestIDs, }: TextFieldProps & Pick<FieldFrameProps, 'copyTestIDs'>) { const [focused, setFocused] = useState(false); const [shown, setShown] = useState(false); const input = useRef<ComponentRef<typeof TextInput>>(null); useImperativeHandle(ref, () => input.current!, []); const trailing = secureTextEntry ? ( <Pressable onPress={() => setShown((s) => !s)} hitSlop={8} accessibilityRole="button" accessibilityLabel={shown ? 'Hide password' : 'Show password'} disabled={disabled}> <Text style={styles.action}>{shown ? 'Hide' : 'Show'}</Text> </Pressable> ) : value && !disabled ? ( <Pressable onPress={() => { onChangeText(''); input.current?.focus(); }} hitSlop={8} accessibilityRole="button" accessibilityLabel={`Clear ${label}`}> <View style={styles.clear}><Text style={styles.clearMark}>×</Text></View> </Pressable> ) : null; return ( <FieldFrame label={label} copyTestIDs={copyTestIDs} variant={variant} minHeight={minHeight} helper={helper} error={error} disabled={disabled} focused={focused} count={maxLength ? [value.length, maxLength] : undefined} trailing={trailing}> <TextInput underlineColorAndroid="transparent" {...inputProps} ref={input} value={value} onChangeText={onChangeText} placeholder={placeholder} placeholderTextColor={colors.outline} editable={!disabled} maxLength={maxLength} secureTextEntry={secureTextEntry && !shown} autoFocus={autoFocus} onFocus={(e) => { setFocused(true); inputProps?.onFocus?.(e); }} onBlur={(e) => { setFocused(false); inputProps?.onBlur?.(e); }} accessibilityLabel={label} accessibilityHint={error ?? helper} style={[styles.input, NO_WEB_RING, disabled && styles.inputDisabled]} /> </FieldFrame> ); } export type FieldFrameProps = { label: string; copyTestIDs?: { label?: string; helper?: string }; variant?: TextFieldVariant; minHeight?: number; helper?: string; error?: string; disabled?: boolean; focused?: boolean; count?: [number, number]; trailing?: ReactNode; children: ReactNode; }; /** The label, box, help line and count around any input. TextField draws this; use it alone to show a state. */ export function FieldFrame({ label, copyTestIDs, variant = 'outlined', minHeight, helper, error, disabled = false, focused = false, count, trailing, children }: FieldFrameProps) { const full = !!count && count[0] >= count[1]; const underlined = variant === 'underlined'; const active = !disabled && (focused || !!error); return ( <View style={[styles.root, minHeight !== undefined && { minHeight }]}> <Text testID={copyTestIDs?.label} style={[styles.label, disabled && styles.muted]}>{label}</Text> <View style={[ styles.box, styles[variant], minHeight !== undefined && styles.grow, active && (underlined ? styles.lineActive : styles.boxActive), active && { borderColor: error ? colors.error : colors.primary }, disabled && (underlined ? styles.lineDisabled : styles.boxDisabled), ]}> <View style={styles.inputWrap}>{children}</View> {trailing} </View> {error || helper || count ? ( <View style={styles.below}> <Text testID={error == null && helper ? copyTestIDs?.helper : undefined} style={[styles.help, !!error && styles.error]} accessibilityLiveRegion={error ? 'polite' : 'none'}>{error ?? helper ?? ''}</Text> {count ? <Text style={[styles.help, styles.count, full && styles.countFull]}>{count[0]}/{count[1]}</Text> : null} </View> ) : null} </View> ); } // The box shows focus, so the browser's own focus ring is turned off on the web. React Native's types have no // 'none' for outlineStyle, but react-native-web passes it through to CSS. const NO_WEB_RING = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as unknown as TextStyle) : null; const styles = StyleSheet.create({ root: { gap: 6 }, grow: { flexGrow: 1 }, label: { fontSize: 14, fontWeight: '500', color: colors.onSurface }, muted: { color: colors.onSurfaceVariant }, box: { minHeight: 50, flexDirection: 'row', alignItems: 'center', gap: 8, }, outlined: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: colors.outline, backgroundColor: colors.surface, }, underlined: { borderBottomWidth: 1, borderColor: colors.outline, paddingTop: 1 }, filled: { paddingHorizontal: 14, borderRadius: radius.md, borderWidth: 1, borderColor: 'transparent', backgroundColor: colors.surfaceVariant }, boxActive: { borderWidth: 2, paddingHorizontal: 13 }, lineActive: { borderBottomWidth: 2, paddingTop: 2 }, lineDisabled: { borderColor: colors.outlineVariant }, boxDisabled: { borderWidth: 0, paddingHorizontal: 15, backgroundColor: colors.surfaceVariant }, inputWrap: { flex: 1, justifyContent: 'center' }, input: { fontSize: 17, color: colors.onSurface, paddingVertical: 12 }, inputDisabled: { color: colors.onSurfaceVariant }, action: { fontSize: 15, fontWeight: '600', color: colors.primary }, clear: { width: 20, height: 20, borderRadius: 10, backgroundColor: colors.outline, alignItems: 'center', justifyContent: 'center' }, clearMark: { marginTop: -2, fontSize: 16, lineHeight: 18, fontWeight: '700', color: colors.surface }, below: { flexDirection: 'row', gap: 12 }, help: { flex: 1, fontSize: 13, color: colors.onSurfaceVariant }, error: { color: colors.error }, count: { flex: 0, fontVariant: ['tabular-nums'] }, countFull: { color: colors.onSurface, fontWeight: '600' }, }); --- end of TextField.tsx --- HOW TO USE IT import { useState } from 'react'; import { TextField } from '@/components/mobilens/TextField'; export function EmailField({ onSubmit }: { onSubmit: (email: string) => void }) { const [email, setEmail] = useState(''); const [error, setError] = useState<string>(); const check = () => { const ok = /^\S+@\S+\.\S+$/.test(email); setError(ok ? undefined : 'Enter an email like name@example.com'); return ok; }; return ( <TextField variant="outlined" label="Email" value={email} onChangeText={(next) => { setEmail(next); setError(undefined); }} error={error} placeholder="name@example.com" inputProps={{ keyboardType: 'email-address', autoCapitalize: 'none', autoCorrect: false, autoComplete: 'email', textContentType: 'emailAddress', returnKeyType: 'next', onSubmitEditing: () => check() && onSubmit(email), }} /> ); } STATES: all 7 must work in the screen where you use it - Empty: when nothing typed and the field is not focused. The label stays above the field; the placeholder is only a hint. - Focused: when the field has focus. The outline or underline uses the focus colour, and the filled field gains a focus ring. The keyboard comes up in the layout the field asks for. - With text: when the field has text and is not focused. A filled, editable field has a clear button. Clearing it returns focus to the input. - Error: when the screen sets error, for example when the user leaves an invalid email. The outline or underline and the message use the error colour. The message replaces the help line. Screen readers announce the message. Check when the user leaves the field or submits, not on every key. - Disabled: when the screen sets disabled. Grey, read-only, and the clear button is hidden. - At the limit: when the text reaches maxLength. The count turns bold and further typing is ignored. - Password: when secureTextEntry is set. Text shows as dots; Show reveals it and turns into Hide. Use the platform's password autofill settings so managers can fill it. ACCESSIBILITY - The label is the field's accessible name; help or the error is read as its hint. - Errors are announced as they appear. - Show / Hide and the clear button are labelled buttons with an 8-point larger tap area. WHEN YOU FINISH List every state and rule above and say how you verified each one.