Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The TextInput field

TextInput is a text input field, the counterpart of input on the web. When the user taps it, the phone shows the on-screen keyboard. The field works as a controlled React component: its value is kept in state.

A simple field

Add a field for the title of a new task to the to-do list:

// app/index.tsx
import { useState } from 'react';
import { StyleSheet, Text, TextInput, View } from 'react-native';
 
export default function Index() {
  const [title, setTitle] = useState('');
 
  return (
    <View style={styles.screen}>
      <TextInput
        style={styles.input}
        value={title}
        onChangeText={setTitle}
        placeholder="New task"
      />
      <Text>You typed: {title}</Text>
    </View>
  );
}
 
const styles = StyleSheet.create({
  screen: { flex: 1, padding: 16, gap: 12 },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 12,
    fontSize: 18,
  },
});

Tap the field and the keyboard appears. Every letter shows up immediately in the "You typed" line. onChangeText receives the whole new string, so setTitle is passed directly, without event.target.value.

Useful props

PropWhat it does
placeholderHint in an empty field
keyboardTypeKeyboard type: 'numeric', 'email-address', 'phone-pad'
secureTextEntryHides characters, for passwords
autoCapitalizeCapital letters: 'none', 'sentences', 'words'
autoCorrectWord autocorrection
multilineMultiline input
maxLengthMaximum length

The right keyboard for the job

For an email field, capital letters are turned off and a keyboard with the @ sign is shown:

// app/index.tsx
<TextInput
  value={email}
  onChangeText={setEmail}
  placeholder="anna@example.com"
  keyboardType="email-address"
  autoCapitalize="none"
/>

The phone opens a keyboard with the @ sign and a dot, and the first letter is not capitalized.

The Done key on the keyboard

returnKeyType changes the label of the return key, and onSubmitEditing is called when it is pressed:

// app/index.tsx
<TextInput
  value={title}
  onChangeText={setTitle}
  returnKeyType="done"
  onSubmitEditing={() => console.log('Add:', title)}
/>

Press Done on the keyboard, and the terminal running npx expo start shows "Add:" with your text. In the next lessons this is where a task gets added.

Common mistake

Expecting the field to be visible right away. TextInput has no border or background by default, so without styles it is invisible on the screen; you only see the cursor after tapping. Always set borderWidth or backgroundColor and padding, as in the first example.

Thanks for reading!

Donate to the site — we work hard for you.