Popular Searches
Popular Course Categories
Popular Courses

Building Interactive Components, Modals, and Animated Lists

Building Interactive Components, Modals, and Animated Lists

Animations, Gestures, and Interactive UI

Building Interactive Components, Modals, and Animated Lists in React Native

Course: React Native Training

Topic: Building Interactive Components, Modals, and Animated Lists

Course Link: React Native Training at JustAcademy

Demo Registration: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction

Interactive components, modals, and animated lists are important parts of modern React Native applications. They help developers create mobile interfaces that respond to user actions, display information clearly, and provide smooth visual feedback.

Interactive components allow users to press buttons, select options, expand cards, switch settings, and perform actions. Modals display focused information or forms above the current screen. Animated lists use transitions to make adding, removing, filtering, or rearranging items feel natural.

React Native provides components such as Pressable, Modal, FlatList, Animated, and LayoutAnimation for these tasks. Additional animation libraries can be used when more advanced transitions or gesture-driven effects are required.

1.1 Learning Objectives

  • Understand interactive components and event handling.
  • Build reusable buttons, cards, and expandable components.
  • Manage UI state using React hooks.
  • Create and control modals.
  • Implement fade and slide animations.
  • Build animated lists using FlatList and Animated.
  • Add and remove list items dynamically.
  • Improve performance, accessibility, and user experience.
  • Troubleshoot common interactive UI problems.

2. Understanding Interactive Components

An interactive component is a UI element that responds to user input. The response may update application state, navigate to another screen, show a dialog, submit information, or animate a visual element.

2.1 Common Interactive Components

Component Purpose Example
Pressable Responds to press interactions. Custom buttons and clickable cards.
TextInput Accepts text input. Search fields and forms.
Switch Changes a Boolean setting. Dark mode or notification settings.
Modal Displays content above the current screen. Confirmation dialogs and edit forms.
FlatList Renders scrollable data efficiently. Product lists and messages.
Animated.View Supports animated view properties. Fading or moving cards.
LayoutAnimation Animates supported layout changes. Expanding panels and changing layouts.

2.2 How Interactive Components Work

  1. The user performs an action, such as pressing a button.
  2. The component receives an event.
  3. An event handler processes the action.
  4. React state is updated when required.
  5. React renders the updated interface.
  6. An animation may communicate the change visually.

3. Managing Component State with useState

The useState hook stores information that can change while a component is in use. When the state changes, React updates the relevant interface.

3.1 Basic State Example

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

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <View style={{ padding: 24 }}>
      <Text>Count: {count}</Text>
      <Pressable
        onPress={() => setCount(previous => previous + 1)}
        style={{
          padding: 14,
          backgroundColor: '#2563EB',
          borderRadius: 8,
          marginTop: 12,
        }}
      >
        <Text style={{ color: '#FFFFFF' }}>Increase Count</Text>
      </Pressable>
    </View>
  );
}

3.2 Understanding the Example

  • useState(0) initializes the counter to zero.
  • count stores the current value.
  • setCount updates the state.
  • The functional updater uses the previous value to calculate the next value safely.
  • The displayed text updates when the state changes.

3.3 Common State Examples

const [isVisible, setIsVisible] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [selectedItem, setSelectedItem] = useState(null);
const [items, setItems] = useState([]);
const [isLoading, setIsLoading] = useState(false);

Use Boolean state for visibility and toggle behavior, arrays for collections of items, and objects when several related values belong together.

4. Building Custom Interactive Buttons

Pressable is a flexible React Native component for handling press interactions. It supports callbacks for pressing and can expose whether the user is currently pressing the element.

4.1 Example of a Custom Button

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

export default function CustomButton({ title, onPress }) {
  return (
    <Pressable
      onPress={onPress}
      accessibilityRole="button"
      accessibilityLabel={title}
      style={({ pressed }) => [
        styles.button,
        pressed && styles.pressed,
      ]}
    >
      <Text style={styles.buttonText}>{title}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#2563EB',
    padding: 14,
    borderRadius: 10,
    alignItems: 'center',
  },
  pressed: {
    opacity: 0.7,
  },
  buttonText: {
    color: '#FFFFFF',
    fontWeight: '600',
  },
});

4.2 Pressable Event Properties

Property Purpose
onPress Runs when a press is completed.
onPressIn Runs when the press begins.
onPressOut Runs when the press interaction ends.
onLongPress Runs when the user holds the element long enough.
disabled Prevents interaction when set to true.
hitSlop Expands the area in which a press can be detected.

5. Creating Expandable Interactive Cards

Expandable cards display a short summary and reveal additional content when the user presses them. They are useful for FAQs, product details, settings, and course information.

5.1 Expandable Card Example

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

export default function ExpandableCard() {
  const [expanded, setExpanded] = useState(false);

  return (
    <View style={{ margin: 16, borderRadius: 12, padding: 16,
      backgroundColor: '#F3F4F6' }}>
      <Pressable
        onPress={() => setExpanded(previous => !previous)}
        accessibilityRole="button"
        accessibilityState={{ expanded }}
      >
        <Text style={{ fontSize: 18, fontWeight: 'bold' }}>
          React Native Features
        </Text>
        <Text>
          {expanded ? 'Hide details ▲' : 'Show details ▼'}
        </Text>
      </Pressable>

      {expanded && (
        <View style={{ marginTop: 12 }}>
          <Text>Components, hooks, navigation, APIs, and animations.</Text>
        </View>
      )}
    </View>
  );
}

This version shows or hides the content immediately. A later section demonstrates how layout changes can be animated.

6. Introduction to Modals

A modal is a component that displays content above the current interface. It is useful when an action requires attention without navigating to a completely different screen.

6.1 Common Uses of Modals

  • Login and registration forms.
  • Delete confirmation dialogs.
  • Product details and image previews.
  • Settings and filter panels.
  • Success, warning, or error messages.
  • Short forms that require user input.

6.2 React Native Modal Properties

Property Description
visible Controls whether the modal is displayed.
animationType Defines the built-in animation: none, fade, or slide.
transparent Allows the modal background to remain transparent.
onRequestClose Handles supported system close requests, including Android hardware back actions.
onShow Runs when the modal has been shown.
onDismiss Runs after dismissal on supported platforms, including iOS.

7. Building a Basic Modal

The following example creates a modal that opens when the user presses a button and closes when the user presses the close button.

import React, { useState } from 'react';
import {
  Modal,
  Pressable,
  StyleSheet,
  Text,
  View,
} from 'react-native';

export default function BasicModal() {
  const [visible, setVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Pressable
        style={styles.openButton}
        onPress={() => setVisible(true)}
      >
        <Text style={styles.buttonText}>Open Modal</Text>
      </Pressable>

      <Modal
        visible={visible}
        transparent
        animationType="fade"
        onRequestClose={() => setVisible(false)}
      >
        <View style={styles.overlay}>
          <View style={styles.modalCard}>
            <Text style={styles.title}>Welcome!</Text>
            <Text>This is a React Native modal.</Text>

            <Pressable
              style={styles.closeButton}
              onPress={() => setVisible(false)}
            >
              <Text style={styles.buttonText}>Close</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  openButton: {
    backgroundColor: '#2563EB',
    padding: 14,
    borderRadius: 8,
  },
  buttonText: {
    color: '#FFFFFF',
    fontWeight: '600',
  },
  overlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
    padding: 20,
  },
  modalCard: {
    width: '100%',
    maxWidth: 360,
    padding: 24,
    borderRadius: 16,
    backgroundColor: '#FFFFFF',
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  closeButton: {
    marginTop: 20,
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
    backgroundColor: '#DC2626',
  },
});

7.1 How the Modal Works

  1. The visible state starts as false, so the modal is hidden.
  2. Pressing Open Modal changes visible to true.
  3. The Modal component displays the overlay and its content.
  4. The fade animation controls how the modal appears.
  5. Pressing Close or invoking onRequestClose changes visible back to false.

8. Creating Confirmation Modals

Confirmation modals help users verify important actions before the application proceeds. They are particularly useful for destructive operations, such as deleting an item.

8.1 Confirmation Modal Example

import React, { useState } from 'react';
import {
  Alert,
  Modal,
  Pressable,
  Text,
  View,
} from 'react-native';

export default function DeleteConfirmation() {
  const [visible, setVisible] = useState(false);

  const confirmDelete = () => {
    setVisible(false);
    Alert.alert('Deleted', 'The item was deleted.');
  };

  return (
    <View style={{ padding: 20 }}>
      <Pressable onPress={() => setVisible(true)}>
        <Text style={{ color: '#DC2626' }}>Delete Item</Text>
      </Pressable>

      <Modal
        visible={visible}
        transparent
        animationType="fade"
        onRequestClose={() => setVisible(false)}
      >
        <View style={{
          flex: 1,
          justifyContent: 'center',
          padding: 24,
          backgroundColor: 'rgba(0,0,0,0.5)',
        }}>
          <View style={{
            padding: 24,
            backgroundColor: '#FFFFFF',
            borderRadius: 12,
          }}>
            <Text style={{ fontSize: 20, fontWeight: 'bold' }}>
              Confirm deletion
            </Text>
            <Text style={{ marginTop: 12 }}>
              Are you sure you want to delete this item?
            </Text>

            <Pressable
              onPress={() => setVisible(false)}
              style={{ marginTop: 20, padding: 10 }}
            >
              <Text>Cancel</Text>
            </Pressable>

            <Pressable
              onPress={confirmDelete}
              style={{ padding: 10 }}
            >
              <Text style={{ color: '#DC2626' }}>
                Confirm Delete
              </Text>
            </Pressable>
          </View>
        </View>
      </Modal>
    </View>
  );
}

In a real application, replace the sample Alert with the actual deletion operation. Handle API failures and avoid closing the modal before the action has reached the appropriate completion state if users need to see the result.

9. Adding Animation to Components

Animation improves the perceived responsiveness of an interface by communicating changes through movement, fading, scaling, and layout transitions.

9.1 Common Animation Effects

  • Fade: Changes opacity to show or hide an element.
  • Slide: Moves a component into or out of view.
  • Scale: Changes the apparent size of an element.
  • Spring: Uses spring-like motion to reach a target value.
  • Layout transition: Animates changes in the positions or sizes of components.

9.2 React Native Animated API

The built-in Animated API can animate properties such as opacity and transforms. With the native driver, supported animations can run without requiring JavaScript to update the animated value on every frame.

import React, { useEffect, useRef } from 'react';
import { Animated, Text } from 'react-native';

export default function FadeInText() {
  const opacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(opacity, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
  }, [opacity]);

  return (
    <Animated.View style={{ opacity }}>
      <Text>Welcome to the application!</Text>
    </Animated.View>
  );
}

When useNativeDriver is true, animate supported non-layout properties such as opacity and transforms. Flexbox layout properties cannot be animated using the native driver through this API.

10. Animated Lists in React Native

Lists display collections of data, such as messages, contacts, tasks, products, and notifications. Animated lists add visual transitions when items appear, disappear, or change position.

10.1 FlatList Overview

FlatList is designed for efficient rendering of scrollable collections. It renders items as needed rather than mounting every item in a large collection simultaneously.

10.2 Important FlatList Properties

Property Purpose
data Array of items to display.
renderItem Function that renders each item.
keyExtractor Returns a stable unique key for each item.
ItemSeparatorComponent Renders a separator between list items.
ListEmptyComponent Displays content when the data array is empty.
ListHeaderComponent Displays a component above the list items.
ListFooterComponent Displays a component below the list items.
extraData Helps FlatList update when relevant external data changes.

11. Building a Basic Interactive List

The following example displays tasks and allows users to add a new item. It introduces the state-management pattern used in animated list interfaces.

import React, { useState } from 'react';
import {
  FlatList,
  Pressable,
  Text,
  TextInput,
  View,
} from 'react-native';

export default function TaskList() {
  const [taskName, setTaskName] = useState('');
  const [tasks, setTasks] = useState([
    { id: '1', title: 'Learn React Native' },
    { id: '2', title: 'Practice components' },
  ]);

  const addTask = () => {
    const title = taskName.trim();

    if (!title) {
      return;
    }

    setTasks(previous => [
      ...previous,
      {
        id: `${Date.now()}-${Math.random()}`,
        title,
      },
    ]);

    setTaskName('');
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <TextInput
        value={taskName}
        onChangeText={setTaskName}
        placeholder="Enter a task"
        style={{
          borderWidth: 1,
          borderColor: '#D1D5DB',
          borderRadius: 8,
          padding: 12,
        }}
      />

      <Pressable
        onPress={addTask}
        style={{
          marginVertical: 12,
          backgroundColor: '#2563EB',
          padding: 12,
          borderRadius: 8,
        }}
      >
        <Text style={{ color: '#FFFFFF' }}>Add Task</Text>
      </Pressable>

      <FlatList
        data={tasks}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={{
            padding: 16,
            marginBottom: 8,
            backgroundColor: '#F3F4F6',
            borderRadius: 8,
          }}>
            <Text>{item.title}</Text>
          </View>
        )}
      />
    </View>
  );
}

This example updates the list data. To animate the appearance of each row, wrap the row in Animated.View and start an animation when the row mounts, or use a supported layout-animation solution.

12. Animating List Items with Animated

One way to animate a row as it appears is to use an opacity value and a small vertical translation. This creates a fade-and-slide effect.

import React, { useEffect, useRef } from 'react';
import { Animated, Text, View } from 'react-native';

function AnimatedRow({ title }) {
  const opacity = useRef(new Animated.Value(0)).current;
  const translateY = useRef(new Animated.Value(12)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(opacity, {
        toValue: 1,
        duration: 250,
        useNativeDriver: true,
      }),
      Animated.timing(translateY, {
        toValue: 0,
        duration: 250,
        useNativeDriver: true,
      }),
    ]).start();
  }, [opacity, translateY]);

  return (
    <Animated.View
      style={{
        opacity,
        transform: [{ translateY }],
        padding: 16,
        marginBottom: 8,
        borderRadius: 8,
        backgroundColor: '#E5EDFF',
      }}
    >
      <Text>{title}</Text>
    </Animated.View>
  );
}

export default AnimatedRow;

Use AnimatedRow as the row component inside FlatList:

<FlatList
  data={tasks}
  keyExtractor={item => item.id}
  renderItem={({ item }) => (
    <AnimatedRow title={item.title} />
  )}
/>

Important: This mount animation runs whenever a row component mounts. Virtualized lists may mount rows again as users scroll, so consider whether repeated animations are desirable. For complex enter, exit, or reordering transitions, consider a list-animation library that supports those behaviors.

13. Animating List Layout Changes

LayoutAnimation can animate supported layout changes caused by state updates. It is useful when adding or removing an item changes the positions of surrounding rows.

13.1 Example with LayoutAnimation

import React, { useState } from 'react';
import {
  LayoutAnimation,
  Platform,
  UIManager,
  FlatList,
  Pressable,
  Text,
  View,
} from 'react-native';

if (
  Platform.OS === 'android' &&
  UIManager.setLayoutAnimationEnabledExperimental
) {
  UIManager.setLayoutAnimationEnabledExperimental(true);
}

export default function AnimatedTaskList() {
  const [items, setItems] = useState([
    { id: '1', title: 'First task' },
    { id: '2', title: 'Second task' },
  ]);

  const removeItem = id => {
    LayoutAnimation.configureNext(
      LayoutAnimation.Presets.easeInEaseOut
    );

    setItems(previous =>
      previous.filter(item => item.id !== id)
    );
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <FlatList
        data={items}
        keyExtractor={item => item.id}
        ListEmptyComponent={
          <Text>No tasks remaining.</Text>
        }
        renderItem={({ item }) => (
          <View style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: 16,
            marginBottom: 8,
            backgroundColor: '#F3F4F6',
            borderRadius: 8,
          }}>
            <Text>{item.title}</Text>
            <Pressable onPress={() => removeItem(item.id)}>
              <Text style={{ color: '#DC2626' }}>Remove</Text>
            </Pressable>
          </View>
        )}
      />
    </View>
  );
}

LayoutAnimation configures a layout transition around a state update. Exact behavior may differ by platform and React Native version. It does not automatically provide every type of row-specific exit animation, so use a specialized animation solution if individual rows need precise enter and exit effects.

14. Adding Remove and Undo Functionality

Interactive lists often need delete or remove actions. A well-designed interface can allow the user to undo a removal before the operation becomes permanent.

14.1 Implementation Approach

  1. Keep the current list in React state.
  2. Store the removed item and its original position.
  3. Animate the layout change when the item is removed.
  4. Show an Undo action.
  5. If Undo is pressed, insert the item back into the list at its previous position.
  6. Clear the temporary removed-item state when the undo period ends.

For a real application, use an appropriate timing mechanism or a clearly defined user action to finish the undo period. If removal affects server data, also handle network errors and restore the item when the request fails.

15. Modals with Interactive Forms

A modal can contain a form that collects user input without navigating away from the current screen. The modal visibility and form values are usually managed with React state.

15.1 Example: Add an Item Using a Modal

import React, { useState } from 'react';
import {
  Modal,
  Pressable,
  Text,
  TextInput,
  View,
} from 'react-native';

export default function AddItemModal() {
  const [visible, setVisible] = useState(false);
  const [name, setName] = useState('');
  const [items, setItems] = useState([]);

  const saveItem = () => {
    const value = name.trim();

    if (!value) {
      return;
    }

    setItems(previous => [
      ...previous,
      { id: `${Date.now()}`, name: value },
    ]);

    setName('');
    setVisible(false);
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <Pressable onPress={() => setVisible(true)}>
        <Text>Add New Item</Text>
      </Pressable>

      <Modal
        visible={visible}
        transparent
        animationType="slide"
        onRequestClose={() => setVisible(false)}
      >
        <View style={{
          flex: 1,
          justifyContent: 'center',
          padding: 20,
          backgroundColor: 'rgba(0,0,0,0.5)',
        }}>
          <View style={{
            padding: 20,
            backgroundColor: '#FFFFFF',
            borderRadius: 12,
          }}>
            <Text style={{
              fontSize: 20,
              fontWeight: 'bold',
            }}>Add Item</Text>

            <TextInput
              value={name}
              onChangeText={setName}
              placeholder="Enter item name"
              style={{
                borderWidth: 1,
                borderColor: '#D1D5DB',
                padding: 12,
                marginTop: 16,
                borderRadius: 8,
              }}
            />

            <Pressable
              onPress={saveItem}
              style={{ marginTop: 16, padding: 12 }}
            >
              <Text>Save</Text>
            </Pressable>

            <Pressable
              onPress={() => setVisible(false)}
              style={{ padding: 12 }}
            >
              <Text>Cancel</Text>
            </Pressable>
          </View>
        </View>
      </Modal>

      {items.map(item => (
        <Text key={item.id} style={{ marginTop: 12 }}>
          {item.name}
        </Text>
      ))}
    </View>
  );
}

15.2 Form Validation

  • Check that required fields are not empty.
  • Trim whitespace before saving text.
  • Display clear validation messages.
  • Disable repeated submissions while saving.
  • Preserve user input if a recoverable error occurs.
  • Close the modal only when the desired operation has succeeded or the user cancels.

16. Improving User Experience

Interactive components should communicate their current state and respond consistently to user input.

  • Use visible feedback when a button is pressed.
  • Show loading indicators during asynchronous operations.
  • Prevent duplicate submissions when necessary.
  • Use suitable modal animations that do not distract users.
  • Provide clear close and cancel actions.
  • Keep list item keys stable and unique.
  • Display an empty-state message when a list has no data.
  • Make important actions accessible through screen readers.
  • Respect reduced-motion preferences where applicable.

17. Performance Optimization

Animations and interactive lists can become expensive when a screen contains many components or performs frequent updates. Use appropriate rendering and animation strategies to keep the interface responsive.

  • Use FlatList for long or frequently updated collections.
  • Provide stable unique keys through keyExtractor.
  • Avoid unnecessary state updates inside frequently executed callbacks.
  • Use memoization when it measurably reduces expensive repeated rendering.
  • Keep list rows lightweight and avoid deeply nested components when possible.
  • Use the native driver for supported Animated properties.
  • Use Reanimated or another suitable animation library for complex transitions when needed.
  • Test performance on real devices with realistic data sizes.

18. Accessibility Considerations

Accessibility makes interactive interfaces usable by people with different abilities and interaction preferences.

  • Provide accessibilityRole for interactive controls where appropriate.
  • Use accessibilityLabel to describe the purpose of buttons.
  • Use accessibilityState to communicate selected, disabled, or expanded states.
  • Ensure modal content has a clear title and a usable close action.
  • Do not rely on color or animation alone to communicate important information.
  • Provide alternative controls for actions that otherwise require gestures.
  • Check screen-reader focus and keyboard behavior where relevant.

19. Common Problems and Solutions

Problem Possible Cause Solution
Modal does not appear. The visible state remains false or the component is rendered incorrectly. Check the state update and Modal placement.
Android back button does not close the modal. onRequestClose is missing or does not update visibility. Implement onRequestClose to close the modal.
List does not update. The original array was mutated or list keys are incorrect. Create a new array with methods such as map, filter, or spread syntax.
Rows display unexpected animations. Rows are remounted or layout transitions are configured incorrectly. Use stable keys and choose an animation strategy suitable for the list.
Animation appears choppy. Too much work occurs during animation or rendering. Reduce unnecessary updates and profile the screen.
Press action happens more than once. Repeated presses trigger the same operation. Track loading state and prevent duplicate submissions where necessary.
Modal content is cut off by the keyboard. The layout does not account for the keyboard. Consider KeyboardAvoidingView or an appropriate scrollable form layout.

20. Mini Project: Interactive Task Manager

Project Objective: Create a task manager that uses interactive controls, a modal form, and animated list transitions.

20.1 Project Features

  • Add a task through a modal.
  • Display tasks in a FlatList.
  • Mark tasks as completed using a pressable control.
  • Remove tasks using a delete action.
  • Animate task appearance and layout changes.
  • Display a confirmation modal before permanent deletion.
  • Show an empty state when no tasks remain.
  • Validate form input and provide feedback.

20.2 Development Steps

  1. Create the React Native project and prepare the screen structure.
  2. Define task data with unique identifiers.
  3. Create a reusable TaskItem component.
  4. Use FlatList to display the collection.
  5. Build a modal containing a TextInput and Save and Cancel controls.
  6. Implement add, complete, and delete actions using immutable state updates.
  7. Add appropriate entry or layout animations.
  8. Test empty, populated, and error states.
  9. Check accessibility and performance.

20.3 Expected Learning Outcomes

By completing the project, learners will practice state management, component reuse, form handling, modal control, list rendering, animation, validation, and debugging.

21. Interview Questions and Answers

Q1. What is an interactive component in React Native?

Answer: It is a component that responds to user input, such as a pressable button, switch, text input, expandable card, or list item.

Q2. What is the purpose of useState?

Answer: useState stores component state and provides a function to update it. When state changes, React can render the updated UI.

Q3. What is a modal?

Answer: A modal presents content above the current screen, commonly for forms, confirmations, and focused tasks.

Q4. What does the animationType prop do?

Answer: It controls the built-in appearance animation of React Native Modal. Supported values include none, fade, and slide.

Q5. What is FlatList used for?

Answer: FlatList efficiently renders scrollable collections by rendering items as needed.

Q6. Why is keyExtractor important?

Answer: It supplies stable, unique identifiers so React can correctly track list items when the data changes.

Q7. What is LayoutAnimation?

Answer: LayoutAnimation configures animations for supported layout changes triggered by UI updates.

Q8. How can a list item be animated when it appears?

Answer: Wrap the row in an animated component and animate properties such as opacity or translation when the row mounts.

Q9. How do you prevent duplicate form submissions?

Answer: Track the submission state, disable the submit control while the operation is in progress, and handle errors appropriately.

Q10. How can you improve animated list performance?

Answer: Use FlatList, stable keys, lightweight row components, suitable animation APIs, and avoid unnecessary state updates.

22. Practice Exercises

  1. Create a custom Pressable button with a pressed-state style.
  2. Build an expandable card that reveals extra information.
  3. Create a modal that collects a user's name.
  4. Build a confirmation modal with Confirm and Cancel actions.
  5. Create a FlatList that supports adding and removing items.
  6. Animate a row using opacity and vertical translation.
  7. Use LayoutAnimation to animate supported layout changes.
  8. Add an empty-state message to a list.
  9. Prevent repeated form submissions while saving.
  10. Test the application using screen readers and different screen sizes.

23. Quick Revision Checklist

  • Pressable handles touch interactions.
  • useState manages changing component data.
  • Modal displays focused content above the current screen.
  • animationType supports built-in modal transitions.
  • FlatList efficiently displays scrollable collections.
  • keyExtractor provides stable item identifiers.
  • Animated can animate supported values such as opacity and transforms.
  • LayoutAnimation can animate supported layout changes.
  • Immutable state updates help React detect collection changes.
  • Accessibility, testing, and performance are essential for production applications.

24. Official Learning Resources

25. Conclusion

Interactive components, modals, and animated lists help developers build React Native applications that are responsive, understandable, and enjoyable to use. Pressable and React state provide the foundation for interaction, Modal supports focused tasks, and FlatList helps display collections efficiently.

By combining these components with Animated or LayoutAnimation, developers can create meaningful transitions when items appear, disappear, or change layout. Good state management, stable list keys, accessibility, and performance testing are essential for reliable results.

To learn more, explore the React Native Training course at JustAcademy, register for a course demo, or visit the JustAcademy website.

whatsapp