Handling User Input & Forms

8 min read

Handling User Input & Forms in React Native

Welcome, intrepid coder! So you've laid out the beautiful interface for your app, but it's a bit of a ghost town. Users can look, but they can't touch (or type). Let's change that. In this guide, we'll transform your static app into a dynamic, interactive experience by mastering user input and forms. It's time to let your users have their say! 🗣️


1. TextInput: Capturing User Keystrokes Safely ⌨️

Definition: TextInput is a fundamental component that allows users to enter text into your app.

The Problem: Your app needs to gather information from the user, like a username, password, or a search query. How do you get that text from their keyboard into your app's state?

The Solution: The TextInput component is your go-to for this. It's a little box that users can tap on to bring up the keyboard and start typing.

Let's look at the most common props you'll use:

  • onChangeText: This is the workhorse. It's a function that gets called every time the user types or deletes something. It receives the new text as an argument, which you can then use to update your component's state.
  • value: This prop displays the text inside the TextInput. You'll typically link this to a state variable.
  • placeholder: This is the grayed-out text that appears in the input field before the user starts typing, giving them a hint about what to enter.
  • keyboardType: This allows you to specify what kind of keyboard to show the user. For example, 'numeric' for numbers or 'email-address' for, well, email addresses.

Under the Hood: When a user types, the native keyboard sends an event to the JavaScript side of your app. React Native then calls the onChangeText function with the updated text.

Example:

Let's create a simple component that takes the user's name and displays it back to them.

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

const NameInput = () => {
  const [name, setName] = useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter your name"
        onChangeText={newName => setName(newName)}
        defaultValue={name}
      />
      <Text style={styles.greeting}>Hello, {name}!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    paddingHorizontal: 10,
  },
  greeting: {
    marginTop: 20,
    fontSize: 18,
  },
});

export default NameInput;

Interesting Fact: The first on-screen keyboard appeared on the Simon Personal Communicator in 1994, a device that was a cell phone, pager, and PDA all in one. It was a bit clunky, but it paved the way for the sleek keyboards we use today!


2. Touchables & Pressables: Handling Taps & Clicks 👆

Definition: Touchable and Pressable are components that can detect and respond to touch gestures.

The Problem: You have a button, an image, or a piece of text that you want the user to be able to tap on to trigger an action. How do you make these elements "pressable"?

The Solution: React Native provides a set of "Touchable" components and the more modern Pressable component to wrap your views and make them respond to touch events.

  • TouchableOpacity: This is a crowd favorite. When pressed, it slightly fades the wrapped view, giving the user a nice visual feedback.
  • TouchableHighlight: This one darkens the wrapped view when pressed. It's great for creating buttons that look like they are being pushed down.
  • TouchableWithoutFeedback: As the name suggests, this one provides no visual feedback. It's useful when you want to handle a tap but don't want any visual change.
  • Pressable: Introduced later, Pressable is the future. It's a more flexible and powerful way to handle touch events. It allows you to define different styles for when the component is pressed, hovered over (on platforms that support it), and more.

The most important prop for all of these is onPress, which is a function that gets called when the user taps on the component.

Example:

Let's create a simple button using TouchableOpacity and Pressable.

javascript
import React from 'react';
import { View, Text, TouchableOpacity, Pressable, Alert, StyleSheet } from 'react-native';

const MyButton = () => {
  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={() => Alert.alert('TouchableOpacity Pressed!')}
      >
        <Text style={styles.buttonText}>Press Me (TouchableOpacity)</Text>
      </TouchableOpacity>

      <Pressable
        style={({ pressed }) => [
          {
            backgroundColor: pressed ? 'rgb(210, 230, 255)' : 'white',
          },
          styles.wrapperCustom,
        ]}
        onPress={() => Alert.alert('Pressable Pressed!')}
      >
        <Text style={styles.buttonText}>Press Me (Pressable)</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#007BFF',
    padding: 10,
    borderRadius: 5,
    marginBottom: 20,
  },
  wrapperCustom: {
    borderRadius: 8,
    padding: 6,
  },
  buttonText: {
    color: 'black',
    fontSize: 16,
    textAlign: 'center',
  },
});

export default MyButton;

Funny Exaggeration: Imagine a world without touch feedback. You tap a button, and... nothing. Did it work? Did the app crash? Are you just tapping a static image? It's like telling a joke and getting no reaction. Awkward and confusing! Touch feedback is the polite laughter your app gives to your user's "jokes".


3. KeyboardAvoidingView: Taming the On-Screen Keyboard 🤺

Definition: KeyboardAvoidingView is a component that automatically adjusts its height, position, or padding in response to the on-screen keyboard.

The Problem: You have a TextInput at the bottom of the screen. When the user taps on it, the keyboard slides up and covers the input field. Now the user can't see what they're typing. Disaster!

The Solution: Wrap your input fields (or your entire screen) in a KeyboardAvoidingView. This component will magically shift your content up so that the keyboard doesn't hide what's important.

The key prop here is behavior. It can be set to:

  • 'padding': The component adds padding to its bottom.
  • 'height': The component's height is reduced.
  • 'position': The component's position is shifted upwards.

The best behavior often depends on your layout and the platform (iOS or Android).

Example:

javascript
import React from 'react';
import { View, TextInput, KeyboardAvoidingView, Platform, StyleSheet } from 'react-native';

const KeyboardFriendlyInput = () => {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={styles.container}
    >
      <TextInput
        placeholder="This input will not be hidden"
        style={styles.input}
      />
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  input: {
    height: 50,
    borderColor: 'gray',
    borderWidth: 1,
    margin: 10,
    paddingHorizontal: 10,
  },
});

export default KeyboardFriendlyInput;

Real-Life Analogy: Imagine you're trying to write on a piece of paper, but your mischievous cat keeps sitting on the bottom half of the page. KeyboardAvoidingView is like gently lifting the paper up so you can see where you're writing, without shooing the cat away entirely.


4. Building Forms & Validating User Input ✅

Definition: A form is a collection of input fields that allow users to submit information. Validation is the process of ensuring that the user's input is correct and complete.

The Problem: You need to collect multiple pieces of information from the user, like a registration form with a username, email, and password. You also need to make sure the user enters valid information (e.g., the email address has an "@" symbol, and the password is long enough).

The Solution: You can build forms by combining TextInput, Pressable, and other input components. For validation, you can write your own logic or use a library to simplify the process.

A Simple Approach:

  1. Use the useState hook to store the values of your form fields.
  2. When the "Submit" button is pressed, run a function that checks the values.
  3. If the values are invalid, update the state to show error messages to the user.

Example:

Let's create a simple login form with basic validation.

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

const LoginForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [emailError, setEmailError] = useState('');
  const [passwordError, setPasswordError] = useState('');

  const handleSubmit = () => {
    let isValid = true;
    if (!email.includes('@')) {
      setEmailError('Please enter a valid email');
      isValid = false;
    } else {
      setEmailError('');
    }

    if (password.length < 6) {
      setPasswordError('Password must be at least 6 characters');
      isValid = false;
    } else {
      setPasswordError('');
    }

    if (isValid) {
      // Submit the form
      console.log('Form submitted:', { email, password });
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Email"
        onChangeText={setEmail}
        value={email}
        keyboardType="email-address"
        autoCapitalize="none"
      />
      {emailError ? <Text style={styles.error}>{emailError}</Text> : null}

      <TextInput
        style={styles.input}
        placeholder="Password"
        onChangeText={setPassword}
        value={password}
        secureTextEntry
      />
      {passwordError ? <Text style={styles.error}>{passwordError}</Text> : null}

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

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
  },
  error: {
    color: 'red',
    marginBottom: 10,
  },
});

export default LoginForm;

Industry Practice: While the above example works for simple cases, for more complex forms, developers often use libraries like Formik or React Hook Form. These libraries help manage form state, handle validation, and deal with form submission more efficiently. It's like having a highly organized sous chef in your kitchen—they handle the prep work so you can focus on the main course!


📚 References for Extra Reading

Challenge

Challenge: Build a Controlled Login Form

Your task is to create a functional and user-friendly login form in React Native. This form will include fields for an email and a password, a submit button, basic validation, and it must properly handle the on-screen keyboard.

Requirements:

  1. Create a functional component named LoginForm.
  2. Use the useState hook to manage the state for email and password input fields.
  3. Render two TextInput components. They must be controlled components, meaning their value and onChangeText props are tied to your state variables.
    • The email input should have a placeholder of "Email" and use the email-address keyboardType.
    • The password input should have a placeholder of "Password" and must obscure the entered text using the secureTextEntry prop.
  4. Add a Pressable component to act as a "Login" button. When pressed, it should trigger a validation function.
  5. Implement the validation logic inside the onPress handler:
    • If either the email or password field is empty, set an error state to display the message "Email and password cannot be empty." in a Text component.
    • If both fields are filled, clear any existing error message and trigger an Alert with the title "Login Successful!".
  6. Wrap your form elements in a KeyboardAvoidingView. Configure its behavior prop to be 'padding' for the iOS platform to prevent the keyboard from covering the inputs.

Expected result

Your final code should be a single React Native component that renders a complete, functional login form. The submitted code must meet the following criteria:

  1. State Management: It must correctly use the useState hook to manage the state for email, password, and an error message.
  2. Controlled Inputs: The TextInput for email and password must be controlled components. Their value prop should be bound to their respective state variables, and their onChangeText prop must update that state.
  3. Input Configuration:
    • The email TextInput must have keyboardType="email-address".
    • The password TextInput must have secureTextEntry={true}.
  4. Keyboard Handling: The entire form must be wrapped in a KeyboardAvoidingView with the behavior prop correctly set based on the platform (Platform.OS === 'ios' ? 'padding' : 'height').
  5. Submission Logic: The Pressable component's onPress prop must trigger a function that:
    • Checks if email or password state variables are empty strings.
    • Sets an error message in the error state if validation fails.
    • Calls Alert.alert('Login Successful!') if validation passes and clears any previous error message.
  6. Conditional Rendering: A Text component for displaying the error message must be rendered conditionally, only appearing when the error state is not empty.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.