← Back to Chapters

Basic Form Using State

? Basic Form Using State

? Quick Overview

A basic form in React Native uses useState to store and update user input. Each input field is connected to state, making the UI reactive and predictable.

? Key Concepts

  • State management with useState
  • Controlled components
  • Handling text input changes
  • Form submission logic

? Syntax / Theory

In React Native, forms are built using components like TextInput and Button. The value of each TextInput is controlled by state, and updates occur using the onChangeText callback.

? Code Example

? View Code Example
// Basic React Native form using useState
import React, { useState } from "react";
import { View, Text, TextInput, Button } from "react-native";

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

const handleSubmit = () => {
console.log("Name:", name);
console.log("Email:", email);
};

return (
<View>
<Text>Name</Text>
<TextInput
value={name}
onChangeText={setName}
/>

<Text>Email</Text>
<TextInput
value={email}
onChangeText={setEmail}
/>

<Button title="Submit" onPress={handleSubmit} />
</View>
);
}

? Live Output / Explanation

What Happens?

When the user types into the inputs, state updates instantly. Pressing the submit button logs the form data.

? Interactive Example: State Simulator

Type in the inputs on the left to see how useState updates the data on the right in real-time.

? Form UI
? Current State Data (JSON)
{ "name": "", "email": "" }

 

? View Logic Behind This
// How the logic works (Conceptual)
const [name, setName] = useState("");

// When user types 'A':
// 1. onChangeText triggers
// 2. setName('A') updates the state
// 3. The component re-renders with value='A'

? Use Cases

  • User registration forms
  • Login screens
  • Feedback and contact forms

✅ Tips & Best Practices

  • Always use controlled inputs
  • Validate input before submission
  • Keep form state minimal

? Try It Yourself

  • Add a password field
  • Show an alert instead of console log
  • Reset the form after submission