Lesson 35 of 60 – Events in React Native
58%

Events in React Native

Events allow users to interact with a React Native application. Examples include pressing a button, typing in a TextInput, changing a switch, selecting an item, touching a component, and scrolling a screen.

Note: In React Native, event handlers are usually passed as functions to component event props such as onPress, onChangeText, onFocus, and onScroll.

1. What are Events?

An event is an action that happens because of user interaction or another activity in the application.

Common examples include:

  • Pressing a button.
  • Typing text.
  • Touching a component.
  • Changing a switch.
  • Scrolling a list.
  • Focusing an input.

2. Why are Events Important?

Without events, most mobile applications would only display static content. Events allow users to control and interact with the UI.

  • Buttons can perform actions.
  • Forms can receive input.
  • Menus can open and close.
  • Data can be selected.
  • Applications can respond to user actions.

3. Event Handler

An event handler is a function that runs when an event occurs.

const handlePress = () => {

    console.log('Button pressed');

};

The function can then be passed to an event prop.

4. onPress Event

The onPress event is commonly used with Button and Pressable.

<Button
    title="Click Me"
    onPress={() =>
        console.log('Clicked')
    }
/>

5. onPress with a Function

const handlePress = () => {

    console.log(
        'Button was pressed'
    );

};

<Button
    title="Save"
    onPress={handlePress}
/>

The function is passed without calling it immediately.

6. onPress with Pressable

<Pressable
    onPress={() =>
        console.log('Pressed')
    }
>

    <Text>
        Press Me
    </Text>

</Pressable>

Pressable provides more control over touch interactions than the basic Button component.

7. Event Handler with useState

const [count, setCount] =
    useState(0);

const handlePress = () => {

    setCount(count + 1);

};

An event can update component state.

8. Button Counter Example

const [count, setCount] =
    useState(0);

return (

    <View>

        <Text>
            Count: {count}
        </Text>

        <Button
            title="Increase"
            onPress={() =>
                setCount(
                    previousCount =>
                        previousCount + 1
                )
            }
        />

    </View>

);

9. onChangeText Event

The onChangeText event is commonly used with TextInput.

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

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter your name"
/>

10. onChangeText with a Function

const handleNameChange = (
    text
) => {

    setName(text);

};

<TextInput
    value={name}
    onChangeText={
        handleNameChange
    }
/>

The new text value is provided to the event handler.

11. onFocus Event

The onFocus event runs when an input receives focus.

const handleFocus = () => {

    console.log(
        'Input focused'
    );

};

<TextInput
    onFocus={handleFocus}
/>

12. onBlur Event

The onBlur event occurs when an input loses focus.

<TextInput
    onBlur={() =>
        console.log(
            'Input lost focus'
        )
    }
/>

It can be useful for validation or changing the appearance of an input.

13. onSubmitEditing Event

The onSubmitEditing event can run when the user submits text from the keyboard.

<TextInput
    placeholder="Enter name"
    onSubmitEditing={() =>
        console.log(
            'Submitted'
        )
    }
/>

14. onLongPress Event

onLongPress can be used with touchable components when the user presses and holds them.

<Pressable
    onLongPress={() =>
        console.log(
            'Long press detected'
        )
    }
>

    <Text>
        Press and Hold
    </Text>

</Pressable>

15. onPressIn and onPressOut

Pressable can respond when a press begins and when it ends.

<Pressable
    onPressIn={() =>
        console.log('Press started')
    }
    onPressOut={() =>
        console.log('Press ended')
    }
>

    <Text>
        Press Me
    </Text>

</Pressable>

16. Press Event Data

Some touch events provide information about the interaction. The event object can contain details about the touch.

const handlePress = (
    event
) => {

    console.log(event);

};

<Pressable
    onPress={handlePress}
>

    <Text>
        Touch Me
    </Text>

</Pressable>

17. Passing Arguments to Event Handlers

Use an arrow function when you need to pass your own value to an event handler.

const handleStudent = (
    name
) => {

    console.log(name);

};

<Button
    title="Student"
    onPress={() =>
        handleStudent('Rahul')
    }
/>

18. Events and Props

A parent component can pass an event handler to a child component through props.

function CustomButton({
    onPress
}) {

    return (

        <Pressable
            onPress={onPress}
        >

            <Text>
                Save
            </Text>

        </Pressable>

    );

}

19. Parent and Child Events

function App() {

    const handleSave = () => {

        console.log(
            'Saved from child'
        );

    };

    return (

        <CustomButton
            onPress={handleSave}
        />

    );

}

This pattern allows a child component to notify its parent when an action occurs.

20. Events with Switch

A Switch commonly uses onValueChange to respond to changes.

const [enabled, setEnabled] =
    useState(false);

<Switch
    value={enabled}
    onValueChange={setEnabled}
/>

When the switch changes, the new boolean value is passed to the handler.

21. Events with ScrollView

ScrollView can respond to scrolling through onScroll.

<ScrollView
    onScroll={() =>
        console.log(
            'Scrolling'
        )
    }
>

    <Text>
        Scrollable Content
    </Text>

</ScrollView>

22. Events with FlatList

Lists can respond to events such as selecting an item or reaching the end of the list.

<FlatList
    data={students}
    renderItem={({
        item
    }) => (

        <Pressable
            onPress={() =>
                handleStudent(item)
            }
        >

            <Text>
                {item.name}
            </Text>

        </Pressable>

    )}
/>

23. Events and Form Validation

const handleSubmit = () => {

    if (email === '') {

        console.log(
            'Email is required'
        );

        return;

    }

    console.log(
        'Form submitted'
    );

};

The submit event can be used to validate form data before continuing.

24. Events and Loading State

const [loading, setLoading] =
    useState(false);

const handleLogin = () => {

    setLoading(true);

    // Perform login operation

};

An event can start an operation and update the loading state.

25. Preventing Repeated Actions

State can be used to disable a button while an operation is in progress.

const [loading, setLoading] =
    useState(false);

<Button
    title={
        loading
            ? 'Saving...'
            : 'Save'
    }
    disabled={loading}
    onPress={handleSave}
/>

26. Common Event Mistakes

  • Calling the event handler during rendering.
  • Using the wrong event prop.
  • Forgetting to provide a function.
  • Forgetting to update state inside the handler when needed.
  • Passing arguments incorrectly.
  • Writing very large event handlers.
  • Ignoring input validation.
  • Allowing repeated actions when an operation is already running.

Incorrect:

onPress={handleSave()}

Correct:

onPress={handleSave}

27. Complete Event Example

import React, {
    useState
} from 'react';

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

export default function App() {

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

    const [message, setMessage] =
        useState('');

    const handleSubmit = () => {

        if (name.trim() === '') {

            setMessage(
                'Please enter your name'
            );

            return;

        }

        setMessage(
            `Hello ${name}`
        );

    };

    return (

        <View style={styles.container}>

            <Text style={styles.title}>
                Event Example
            </Text>

            <TextInput
                style={styles.input}
                value={name}
                onChangeText={setName}
                placeholder="Enter your name"
                onFocus={() =>
                    console.log(
                        'Input focused'
                    )
                }
                onBlur={() =>
                    console.log(
                        'Input blurred'
                    )
                }
            />

            <Pressable
                style={styles.button}
                onPress={handleSubmit}
            >

                <Text
                    style={styles.buttonText}
                >
                    Submit
                </Text>

            </Pressable>

            <Text style={styles.message}>
                {message}
            </Text>

        </View>

    );

}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        padding: 20,
        justifyContent: 'center'
    },

    title: {
        fontSize: 26,
        fontWeight: 'bold',
        marginBottom: 20
    },

    input: {
        borderWidth: 1,
        borderColor: '#CBD5E1',
        borderRadius: 8,
        padding: 12
    },

    button: {
        marginTop: 15,
        padding: 14,
        borderRadius: 8,
        backgroundColor: '#2563EB',
        alignItems: 'center'
    },

    buttonText: {
        color: 'white',
        fontWeight: 'bold'
    },

    message: {
        marginTop: 20,
        fontSize: 18
    }

});

28. Event Handling Best Practices

  • Use clear and meaningful event handler names.
  • Keep event handlers focused on one task.
  • Use state when an event needs to change the UI.
  • Validate user input before processing it.
  • Disable actions when necessary during loading.
  • Use function props for reusable child components.
  • Avoid unnecessary complex logic directly inside JSX.
  • Use the appropriate event prop for each component.

29. Common React Native Events

Event Common Use
onPress Button and touch actions
onLongPress Long touch interaction
onPressIn When a press begins
onPressOut When a press ends
onChangeText TextInput changes
onFocus Input receives focus
onBlur Input loses focus
onSubmitEditing Input submission
onValueChange Switch value changes
onScroll Scroll interaction

30. Complete Event Handling Workflow

Create UI Component
        ↓
Choose the Required Event
        ↓
Create Event Handler
        ↓
Attach Handler to Event Prop
        ↓
User Performs Action
        ↓
Event Handler Runs
        ↓
Read Event Data if Needed
        ↓
Update State or Perform Action
        ↓
React Updates the UI
        ↓
Continue Application Workflow

Events are essential for creating interactive React Native applications. By combining event handlers with props and state, you can build buttons, forms, menus, lists, login screens and complete mobile application interactions.

📌 Key Points

  • Events allow users to interact with a React Native application.
  • Event handlers are functions that respond to events.
  • onPress is commonly used for touch actions.
  • onChangeText is commonly used with TextInput.
  • onFocus and onBlur handle input focus changes.
  • Functions can be passed to child components through props.
  • Events can update component state.
  • Pressable supports several touch-related event handlers.
  • Events can be used for form validation and application logic.
  • Proper event handling makes React Native applications interactive.

🧠 Quick Quiz

Question: Which event is commonly used to handle text changes in a React Native TextInput?