0
0
React Nativemobile~5 mins

TextInput with controlled state in React Native

Choose your learning style9 modes available
Introduction

We use controlled TextInput to keep track of what the user types. This helps us respond to input changes immediately.

When you want to show what the user types somewhere else on the screen.
When you need to validate input as the user types, like checking email format.
When you want to clear or reset the input field from code.
When you want to enable or disable buttons based on input content.
Syntax
React Native
const [text, setText] = useState('');

<TextInput
  value={text}
  onChangeText={setText}
  placeholder="Type here"
/>

The value prop sets the input's current text.

The onChangeText prop updates the state when the user types.

Examples
This example controls a name input field.
React Native
const [name, setName] = useState('');

<TextInput
  value={name}
  onChangeText={setName}
  placeholder="Enter your name"
/>
This example controls an email input with a keyboard optimized for emails.
React Native
const [email, setEmail] = useState('');

<TextInput
  value={email}
  onChangeText={setEmail}
  keyboardType="email-address"
  placeholder="Enter your email"
/>
Sample App

This app shows a text input box. Whatever you type appears below in real time. The input is controlled by React state.

React Native
import React, { useState } from 'react';
import { View, TextInput, Text, StyleSheet } from 'react-native';

export default function App() {
  const [text, setText] = useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={text}
        onChangeText={setText}
        placeholder="Type something"
        accessibilityLabel="Input field"
      />
      <Text style={styles.output}>You typed: {text}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
    backgroundColor: '#fff'
  },
  input: {
    height: 40,
    borderColor: '#888',
    borderWidth: 1,
    paddingHorizontal: 10,
    marginBottom: 20,
    borderRadius: 5
  },
  output: {
    fontSize: 16
  }
});
OutputSuccess
Important Notes

Always set value and onChangeText together to keep input controlled.

Controlled inputs help keep your app data in sync with what the user sees.

Use accessibilityLabel for better screen reader support.

Summary

Controlled TextInput means React state holds the input text.

Use value and onChangeText props to control input.

This lets you respond instantly to user typing and keep UI updated.