React-Expo

Lesson 4 of 9

Handling User Input and State

State management works exactly the same as web React (useState, useReducer), what changes are the native components you use to capture input.

Text input

import { useState } from 'react';
import { TextInput, View } from 'react-native';

export default function SearchBox() {
  const [query, setQuery] = useState('');

  return (
    <View>
      <TextInput
        value={query}
        onChangeText={setQuery}
        placeholder="Search courses..."
        style={{ borderWidth: 1, borderRadius: 8, padding: 10 }}
      />
    </View>
  );
}

Note onChangeText, not onChange, React Native's TextInput hands your callback the new string directly, there's no event.target.value to unwrap like on the web.

Buttons and touchables

import { Pressable, Text } from 'react-native';

function LikeButton({ onPress }) {
  return (
    <Pressable onPress={onPress} style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}>
      <Text>❤️ Like</Text>
    </Pressable>
  );
}

Pressable is the modern, flexible way to make anything tappable, style can be a function that receives the current interaction state (pressed, hovered on web), letting you add feedback like a subtle opacity change without any extra state of your own.

Forms are just state

There's no <form onSubmit> on mobile, a "form" is just a collection of state variables and a button that reads them when pressed:

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  function handleSubmit() {
    console.log('logging in with', email, password);
  }

  return (
    <View>
      <TextInput value={email} onChangeText={setEmail} placeholder="Email" />
      <TextInput value={password} onChangeText={setPassword} placeholder="Password" secureTextEntry />
      <Pressable onPress={handleSubmit}><Text>Log in</Text></Pressable>
    </View>
  );
}

secureTextEntry masks the input, the native equivalent of type="password".

📝 Input & State Quiz

Passing score: 70%
  1. 1.Which prop does TextInput use to react to typing, instead of onChange?

  2. 2.TextInput's change handler receives the raw event object, and you must read event.target.value from it.

  3. 3.Setting ____ to true on a TextInput masks the typed characters, like a password field.