Forms in React Native

 In React Native, forms are a fundamental part of most mobile applications, allowing users to input and submit data. Here’s an overview of creating and managing forms in React Native:


1. Basic Components for Forms

React Native provides several built-in components that are commonly used in forms:

  • TextInput: For text input fields.
  • Button: For submission or other actions.
  • Picker: For dropdown selection.
  • Switch: For toggles.
  • Slider: For numeric range input.
  • TouchableOpacity: For custom buttons or areas.

2. Controlled Components

React Native forms typically use controlled components, where the form's state is managed in a React state object.

Example:

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

const FormExample = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleSubmit = () => {
    alert(`Name: ${name}, Email: ${email}`);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Name:</Text>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
        placeholder="Enter your name"
      />
      <Text style={styles.label}>Email:</Text>
      <TextInput
        style={styles.input}
        value={email}
        onChangeText={setEmail}
        placeholder="Enter your email"
        keyboardType="email-address"
      />
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
};

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

export default FormExample;