# TextInput, Forms and the Keyboard — React Native

Source: https://www.skillbyai.com/en/react-native/l-input

> Typing on a phone.

## Controlled inputs and keyboard handling

**TextInput** works like a controlled input in React: hold the text in state, pass it as `value` and update it in `onChangeText`. Mobile-specific props shape the keyboard: `keyboardType` (`email-address`, `numeric`, `phone-pad`), `autoCapitalize`, `autoComplete`, `secureTextEntry` for passwords, `returnKeyType` and `onSubmitEditing` to move between fields. The on-screen keyboard can cover inputs, so wrap forms in **KeyboardAvoidingView** (commonly `behavior="padding"` on iOS and often `"height"` or nothing on Android, depending on your window settings) and use `keyboardShouldPersistTaps="handled"` on scroll views so taps on buttons work while the keyboard is open. Form libraries such as React Hook Form work with React Native too.

## A login form

Controlled inputs that move focus and avoid the keyboard.

```tsx
import { useRef, useState } from "react";
import { KeyboardAvoidingView, Platform, ScrollView, TextInput, Pressable, Text } from "react-native";

export function LoginForm({ onSubmit }: { onSubmit: (email: string, password: string) => void }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const passwordRef = useRef<TextInput>(null);

  return (
    <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === "ios" ? "padding" : undefined}>
      <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{ padding: 24, gap: 12 }}>
        <TextInput
          value={email}
          onChangeText={setEmail}
          placeholder="Email"
          keyboardType="email-address"
          autoCapitalize="none"
          autoComplete="email"
          returnKeyType="next"
          onSubmitEditing={() => passwordRef.current?.focus()}
        />
        <TextInput
          ref={passwordRef}
          value={password}
          onChangeText={setPassword}
          placeholder="Password"
          secureTextEntry
          returnKeyType="go"
          onSubmitEditing={() => onSubmit(email, password)}
        />
        <Pressable accessibilityRole="button" onPress={() => onSubmit(email, password)}>
          <Text>Sign in</Text>
        </Pressable>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
```

## Pick the right keyboard

Setting keyboardType, autoComplete and autoCapitalize correctly saves users effort and enables password managers and one-time-code autofill.

**Quiz:** Which TextInput prop receives the new text on every change?

- [ ] onKeyUp
- [ ] onInput
- [x] onChangeText
- [ ] onValue

*Answer:* onChangeText. onChangeText passes the string directly.
