0
0
React Nativemobile~15 mins

TextInput component in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Text Input
This screen lets the user type text into a box and shows the typed text below it.
Target UI
-------------------------
| Simple Text Input      |
|-----------------------|
| [___________________] |
|                       |
| Typed text appears here|
-------------------------
Add a TextInput where the user can type text.
Show the typed text below the TextInput in real time.
Use a placeholder text 'Type here...'.
Ensure the TextInput has a border and some padding.
Starter Code
React Native
import React, { useState } from 'react';
import { View, TextInput, Text, StyleSheet } from 'react-native';

export default function SimpleTextInput() {
  // TODO: Add state to store typed text

  return (
    <View style={styles.container}>
      {/* TODO: Add TextInput here */}
      {/* TODO: Show typed text here */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
  },
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState } from 'react';
import { View, TextInput, Text, StyleSheet } from 'react-native';

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

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Type here..."
        onChangeText={setText}
        value={text}
        accessibilityLabel="Text input field"
      />
      <Text style={styles.displayText}>{text}</Text>
    </View>
  );
}

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

We use React's useState hook to keep track of the text the user types. The TextInput component has a placeholder to show a hint. The onChangeText updates the state whenever the user types. The typed text is shown below in a Text component. Styles add a border and padding for a clear input box. Accessibility label helps screen readers.

Final Result
Completed Screen
-------------------------
| Simple Text Input      |
|-----------------------|
| [Type here...       ] |
|                       |
| Hello world           |
-------------------------
User taps the input box and types text.
Typed text appears instantly below the input box.
Stretch Goal
Add a clear button that erases the typed text when pressed.
💡 Hint
Use a button next to the TextInput that calls setText('') when pressed.