0
0
React Nativemobile~5 mins

TextInput component in React Native

Choose your learning style9 modes available
Introduction

The TextInput component lets users type text into your app. It is how you get information from people.

When you want to ask the user for their name or email.
When you need the user to enter a password or PIN.
When you want to let users write comments or messages.
When you want to search for something by typing keywords.
When you want to collect any text input from the user.
Syntax
React Native
import { TextInput } from 'react-native';

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

value holds the current text inside the input.

onChangeText is a function called when the user types or deletes text.

Examples
A simple input with placeholder text.
React Native
<TextInput placeholder="Enter your name" />
Controlled input that updates state as user types.
React Native
const [text, setText] = useState('');

<TextInput
  value={text}
  onChangeText={setText}
  placeholder="Type something"
/>
Input that hides typed text for passwords.
React Native
<TextInput
  secureTextEntry={true}
  placeholder="Enter password"
/>
Sample App

This app shows a text input where you can type your name. Below it, it greets you with the name you typed. If you type nothing, it says "Hello, stranger!".

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

export default function App() {
  const [name, setName] = useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter your name"
        value={name}
        onChangeText={setName}
        accessibilityLabel="Name input"
      />
      <Text style={styles.greeting}>Hello, {name || 'stranger'}!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20
  },
  input: {
    borderColor: '#888',
    borderWidth: 1,
    padding: 10,
    fontSize: 18,
    borderRadius: 5
  },
  greeting: {
    marginTop: 20,
    fontSize: 20
  }
});
OutputSuccess
Important Notes

Always add accessibilityLabel for screen readers.

Use secureTextEntry for password fields to hide text.

Style your TextInput for better user experience and visibility.

Summary

The TextInput component lets users type text in your app.

Use value and onChangeText to control the input.

Remember to add placeholders and accessibility labels.