← Back to Chapters

Populate Data in Input

? Populate Data in Input

? Quick Overview

In React Native, populating data inside an input field is commonly done using the TextInput component along with state management. This is useful when editing existing data, showing fetched API values, or setting default input values.

? Key Concepts

  • Using useState to store input values
  • Binding state to TextInput via the value prop
  • Updating state using onChangeText
  • Pre-filling input fields with existing data

? Syntax / Theory

To populate data in a React Native input:

  1. Create a state variable using useState
  2. Assign that state to the value prop
  3. Update the state using onChangeText
? View Code Example
// Import required hooks and components
import React, { useState } from "react";
import { View, TextInput, StyleSheet, Button } from "react-native";

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

  // Function to simulate fetching new data
  const loadProfile = () => {
    setName("Alice Wonderland");
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName} 
        placeholder="Enter your name"
      />
      <Button title="Load Profile" onPress={loadProfile} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20 },
  input: {
    borderWidth: 1,
    borderColor: "#ccc",
    padding: 10,
    marginBottom: 10,
    borderRadius: 5
  }
});

? Live Output / Explanation

The input field is automatically populated with the text John Doe. When the user types, the value updates instantly because the input is controlled by React state.

? Interactive Example: State Simulator

Use the buttons below to simulate fetching data from a database and populating the React Native inputs. Watch how the State (Memory) updates instantly when you type, and how the Input updates when you load data.

// Virtual React State
{ "name": "", "role": "" }

? Use Cases

  • Edit profile screens
  • Prefilled login or signup forms
  • Updating fetched API data
  • Form validation and previews

? Tips & Best Practices

  • Always use controlled inputs for better state control
  • Initialize state with default or fetched values
  • Avoid uncontrolled inputs in complex forms
  • Use useEffect when populating data from APIs

? Try It Yourself

  • Change the default name to your own
  • Add another input for email
  • Populate input using API data
  • Clear the input with a button