Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 71 ยท Components and Interaction

Text and TextInput

Master the Text and TextInput components in React Native: truncation, nesting, fonts, keyboard types, secure entry, and controlled inputs, with live stand-ins.

Almost every screen is made of two things: text you read and text you type. React Native gives you two components for them, Text and TextInput. They look simple, but they carry many of the details that make an app feel native: truncation with an ellipsis, text that respects the user's font-size setting, a keyboard that switches to digits for a phone number, and a field that hides a password.

You met Text briefly in core components. Here we go deeper, then turn to input, where React's controlled-component idea from Forms and Inputs applies almost unchanged.

What runs on this site. Text and TextInput are native components, so the real code is read-only here. The runnable examples are stand-ins: HTML elements that imitate numberOfLines, nesting and a controlled input with the same props and logic. Keyboards, autofill and font scaling only exist on a device or simulator.

The Text component

Everything that shows characters must be inside a Text. Styles for text (fontSize, color, fontWeight, lineHeight, textAlign) are set on Text, not on View, and, unlike on the web, they are not inherited from a parent View. They are inherited only from a parent Text.

JSX
import { Text, View } from 'react-native';

export function Article() {
  return (
    <View>
      <Text style={{ fontSize: 22, fontWeight: '700' }}>Pocket guide</Text>
      <Text style={{ fontSize: 16, lineHeight: 24 }}>
        You can <Text style={{ fontWeight: '700' }}>nest</Text> text to style
        part of a sentence, and the inner text inherits the outer text's style.
      </Text>
    </View>
  );
}

Nested Text is how you make bold words, colored words or tappable links inside a sentence. A nested Text can even take its own onPress. Nested text is laid out as part of the same paragraph, while a View between pieces of text would break the flow.

Truncation and selection

Long text needs a plan. numberOfLines limits how many lines are drawn, and ellipsizeMode chooses where the missing part is replaced with an ellipsis.

JSX
<Text numberOfLines={2} ellipsizeMode="tail">
  {article.summary}
</Text>

ellipsizeMode can be tail (the default), head, middle or clip. Middle truncation is handy for file names, where the start and the extension both matter. Add selectable and the user can long-press to select and copy the text, which is off by default.

Fonts and the user's settings

By default text uses the platform's system font (San Francisco on iOS, Roboto on most Android devices). Custom fonts are loaded first (for example with expo-font, covered in Theming and Dark Mode) and then referenced by name in fontFamily. One native-specific catch: with custom fonts, bold is usually a separate font file with its own name, so you set fontFamily: 'Inter-Bold' rather than relying on fontWeight.

Phones let people raise their system font size. By default, Text scales with that setting (allowFontScaling is on). That is good for accessibility, but it can break fixed-height layouts, so test with large text. You can cap the growth with maxFontSizeMultiplier, and adjustsFontSizeToFit shrinks text to fit one line when it would otherwise overflow.

Text props to know

numberOfLines Limit lines and add an ellipsis.
ellipsizeMode head, middle, tail or clip.
selectable Let people copy the text.
allowFontScaling Follow the user's font size.
1 / 2
Truncation and nested text (stand-in)

The TextInput component

TextInput is a native text field. On its own it is uncontrolled, like a plain HTML input. The recommended pattern is the same as in web React: hold the value in state and pass it back, so your component is the single source of truth.

JSX
import { useState } from 'react';
import { TextInput, View, Text } from 'react-native';

export function NameField() {
  const [name, setName] = useState('');
  return (
    <View>
      <TextInput
        value={name}
        onChangeText={setName}
        placeholder="Your name"
        autoCapitalize="words"
        autoCorrect={false}
        style={{ borderWidth: 1, borderColor: '#cbd5e1', padding: 10, borderRadius: 8 }}
      />
      <Text>Hello, {name || 'stranger'}!</Text>
    </View>
  );
}

Notice onChangeText. Unlike the web's onChange, it receives the new string directly, not an event object. If you need the event, use onChange, but onChangeText is what you reach for ninety percent of the time. Style the placeholder with placeholderTextColor, and remember that a field has no border or padding until you give it some.

Choosing the right keyboard

The biggest win of a native input is the keyboard. Tell the system what is being typed and it shows the best layout.

JSX
<TextInput keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
<TextInput keyboardType="phone-pad" />
<TextInput keyboardType="decimal-pad" />
<TextInput secureTextEntry autoComplete="password" />
  • keyboardType: default, email-address, numeric, decimal-pad, phone-pad, url and more. There is also the newer inputMode prop, which mirrors the web's attribute. Note that keyboardType changes the keyboard only; it does not validate what the user pastes.
  • secureTextEntry hides characters as dots and turns off suggestions. Pair it with autoComplete="password" (and textContentType on iOS) so password managers can fill the field.
  • autoCapitalize: none for emails and usernames, words for names, sentences (the default) for prose.
  • returnKeyType changes the label of the return key (next, done, search, go), and onSubmitEditing fires when it is pressed.
  • multiline turns the field into a text area, and maxLength caps the input.
  • editable={false} makes it read-only, and a ref gives you focus(), blur() and clear().

Controlled inputs in practice

Because every keystroke passes through your code, a controlled input can transform text as it is typed: strip non-digits, format a phone number, limit a length or normalize case.

JSX
function onChangePhone(text) {
  const digits = text.replace(/\D/g, '').slice(0, 10);
  setPhone(digits);
}

Keep the raw value in state and format it for display, instead of storing the formatted string and parsing it again later. We will build whole forms with validation in Forms and Validation.

A controlled input with formatting

Moving between fields

On a form, pressing the return key should move focus to the next field instead of closing the keyboard. You do it with refs and onSubmitEditing:

JSX
const passwordRef = useRef(null);

<TextInput
  returnKeyType="next"
  onSubmitEditing={() => passwordRef.current?.focus()}
  submitBehavior="submit"
/>
<TextInput ref={passwordRef} secureTextEntry returnKeyType="done" />

submitBehavior="submit" keeps the keyboard open on submit (older versions called this blurOnSubmit={false}). Check the current React Native documentation for the exact name in your version.

Common mistakes

  • Fields with no size. A TextInput with no padding or border looks invisible. Always style it.
  • Treating keyboardType as validation. Users can paste anything, and a hardware keyboard ignores it. Validate in code.
  • Fixed-height text. Large font settings can clip text. Prefer minHeight and padding over height.
  • Forgetting autoCapitalize="none" on email fields, so "Alice@..." is typed with a capital A.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the onChangeText callback of TextInput receive?

    onChangeText is called with the new string directly. If you want the full event object, use onChange instead.
  2. 2. Which props limit a long paragraph to three lines and put the ellipsis in the middle?

    numberOfLines sets the maximum lines and ellipsizeMode picks head, middle, tail or clip. The other names do not exist on Text.
  3. 3. Where does text styling such as fontSize get inherited from?

    React Native has no cascade. Nested Text components inherit text styles from the Text that contains them, but a View does not pass its styles down to text.
  4. 4. Why is keyboardType="numeric" not enough to guarantee numeric input?

    keyboardType only chooses which keyboard is shown. Pasted text and hardware keyboards bypass it, so validate or filter the value in onChangeText.

Summary

  • Text must be inside Text; text styles inherit only from a parent Text, and nested Text styles parts of a sentence.
  • Use numberOfLines and ellipsizeMode to truncate, selectable to allow copying, and keep font scaling on for accessibility.
  • TextInput is controlled with value and onChangeText, which gives you a plain string.
  • Pick the right keyboard with keyboardType, autoCapitalize, secureTextEntry and returnKeyType, but still validate the value.
  • Move between fields with refs and onSubmitEditing.
  • On this site the components are read-only and the TryIts are HTML stand-ins for their behavior.

Next, make things tappable with Pressable, Buttons and Touch Feedback.