Understanding React Native Core Components
Course: React Native Training
Topic: Understanding React Native Core Components
Course Link: React Native Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to React Native Core Components
React Native is a framework used to build mobile applications for Android and iOS using JavaScript or TypeScript and React. Instead of building every interface element from scratch, developers use reusable components to create screens, layouts, forms, lists, buttons, and other interactive elements.
Core Components are the built-in components provided by React Native. They connect the React component model to native user-interface elements on the target platform. For example, the View component provides a container for other elements, while Text displays text and TextInput allows users to enter information.
Core Components are the foundation of most React Native applications. Understanding them helps developers create interfaces that are reusable, maintainable, responsive, and accessible.
Why Core Components are important
- They provide ready-to-use building blocks for mobile interfaces.
- They reduce the need to implement common UI behavior from scratch.
- They support interaction with native Android and iOS interface elements.
- They can be combined to create reusable components and complete screens.
- They support styling, layouts, touch interactions, and accessibility.
- They help developers maintain a consistent application structure.
2. Learning Objectives
After studying this topic, learners should be able to:
- Explain the purpose of React Native Core Components.
- Use
View and Text to create basic layouts.
- Display local and remote images with
Image.
- Collect user input with
TextInput.
- Handle user interactions with
Button and Pressable.
- Create scrollable content using
ScrollView.
- Render efficient data lists using
FlatList and SectionList.
- Use
Switch, ActivityIndicator, Alert, and Modal.
- Style components with
StyleSheet and Flexbox.
- Combine multiple Core Components into a practical mobile screen.
3. What Is a React Native Component?
A component is a reusable piece of an application's interface. It can display information, accept user input, respond to interactions, or contain other components.
For example, a shopping application may contain:
- A header displaying the application name.
- A search input for finding products.
- Product cards containing images and prices.
- Buttons for adding products to a cart.
- A list displaying available products.
- A modal showing product details.
Each part can be created by combining React Native Core Components and custom components.
Basic component example
import React from 'react';
import { View, Text } from 'react-native';
export default function WelcomeScreen() {
return (
<View>
<Text>Welcome to React Native!</Text>
</View>
);
}
In this example, View acts as the container and Text displays the message.
4. Categories of Core Components
React Native includes components for basic layouts, user interactions, scrolling lists, feedback, and platform-specific functionality.
| Category |
Components |
Purpose |
| Basic layout and content |
View, Text, Image |
Arrange elements and display information. |
| User input |
TextInput, Switch |
Collect text and toggle values. |
| Touch interactions |
Button, Pressable |
Respond to user actions. |
| Scrolling and lists |
ScrollView, FlatList, SectionList |
Display scrollable content and collections. |
| Feedback |
ActivityIndicator, Alert |
Show progress and messages. |
| Overlays |
Modal |
Display content above the main interface. |
| Layout and styling |
StyleSheet |
Organize and reuse component styles. |
| Keyboard and device layout |
KeyboardAvoidingView, SafeAreaView |
Help manage keyboard and screen boundaries. |
5. The View Component
The View component is one of the most fundamental React Native components. It acts as a container for other elements and supports layout, styling, touch handling, and accessibility properties.
A View can contain other views and components, allowing developers to organize an interface into logical sections.
Example
import React from 'react';
import { View, Text } from 'react-native';
export default function ProfileCard() {
return (
<View>
<Text>User Profile</Text>
<Text>Name: Rahul</Text>
<Text>Role: Developer</Text>
</View>
);
}
Common View properties
| Property |
Purpose |
style |
Applies layout and visual styles. |
onLayout |
Responds when the component's layout is calculated or changes. |
accessible |
Controls whether the view is treated as an accessibility element. |
accessibilityLabel |
Provides a descriptive label for assistive technologies when applicable. |
testID |
Provides an identifier useful for automated testing. |
When to use View
- To group related components.
- To create cards, rows, columns, and sections.
- To apply padding, spacing, borders, and backgrounds.
- To organize screen layouts using Flexbox.
6. The Text Component
The Text component displays text in a React Native application. It supports styling, nested text, and text-related interaction properties.
Unlike ordinary HTML, React Native generally requires visible text to be placed inside a Text component rather than directly inside a View.
Example
import React from 'react';
import { View, Text } from 'react-native';
export default function TextExample() {
return (
<View>
<Text>Welcome to the application.</Text>
<Text>Learn React Native step by step.</Text>
</View>
);
}
Styling Text
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default function StyledText() {
return (
<View>
<Text style={styles.heading}>Course Details</Text>
<Text style={styles.description}>
Learn mobile application development.
</Text>
</View>
);
}
const styles = StyleSheet.create({
heading: {
fontSize: 24,
fontWeight: 'bold'
},
description: {
fontSize: 16,
lineHeight: 24
}
});
Common Text properties and styles
style: applies font size, color, weight, alignment, and other text styles.
numberOfLines: limits the number of displayed lines.
ellipsizeMode: controls how truncated text is indicated where supported.
selectable: allows users to select text.
onPress: responds to a press on the text.
allowFontScaling: controls whether the text respects system font scaling.
7. The Image Component
The Image component displays images in React Native. Images may be included in the project or loaded from a remote URL.
7.1 Displaying a local image
Local images can be imported through a static require() call. The file must exist at the specified path.
import React from 'react';
import { View, Image } from 'react-native';
export default function LocalImageExample() {
return (
<View>
<Image
source={require('./assets/logo.png')}
style={{ width: 120, height: 120 }}
resizeMode="contain"
accessibilityLabel="Application logo"
/>
</View>
);
}
7.2 Displaying a remote image
import React from 'react';
import { Image, View } from 'react-native';
export default function RemoteImageExample() {
return (
<View>
<Image
source={{
uri: 'https://reactnative.dev/img/tiny_logo.png'
}}
style={{ width: 100, height: 100 }}
resizeMode="contain"
accessibilityLabel="React Native logo"
/>
</View>
);
}
Remote images should use an appropriate network URL, and their dimensions should be specified through styles or the required layout constraints.
Common Image properties
| Property |
Purpose |
source |
Specifies a local image resource or remote image URI. |
style |
Controls width, height, border radius, and other supported styles. |
resizeMode |
Controls how the image fits within its container. |
onLoad |
Runs when the image has loaded successfully. |
onError |
Responds when image loading fails. |
accessible |
Controls accessibility treatment. |
accessibilityLabel |
Provides a useful description when needed. |
Common resize modes
cover: fills the container while preserving the image aspect ratio; some content may be cropped.
contain: fits the entire image inside the container while preserving its aspect ratio.
stretch: stretches the image to fill the container, potentially changing its proportions.
center: centers the image without scaling it to fill the container.
repeat: repeats the image to cover the container where supported.
8. The TextInput Component
The TextInput component allows users to enter text using the device keyboard. It is commonly used for login forms, search bars, registration pages, comments, and contact forms.
Example: Basic text input
import React, { useState } from 'react';
import { View, Text, TextInput } from 'react-native';
export default function InputExample() {
const [name, setName] = useState('');
return (
<View>
<Text>Enter your name:</Text>
<TextInput
value={name}
onChangeText={setName}
placeholder="Type your name"
/>
<Text>Your name: {name}</Text>
</View>
);
}
Important TextInput properties
| Property |
Purpose |
value |
Sets the current value of a controlled input. |
onChangeText |
Receives the updated text as a string. |
placeholder |
Displays guidance when the field is empty. |
keyboardType |
Requests a suitable keyboard, such as numeric or email. |
secureTextEntry |
Obscures input such as a password. |
multiline |
Allows multiple lines of text. |
maxLength |
Limits the number of characters entered. |
autoCapitalize |
Controls automatic capitalization behavior. |
editable |
Controls whether the user can edit the field. |
onSubmitEditing |
Responds when the keyboard's submit action is triggered. |
Example: Login form inputs
import React, { useState } from 'react';
import { View, Text, TextInput } from 'react-native';
export default function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<View>
<Text>Email</Text>
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Enter email"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>
<Text>Password</Text>
<TextInput
value={password}
onChangeText={setPassword}
placeholder="Enter password"
secureTextEntry
/>
</View>
);
}
Real login forms should also validate inputs and handle authentication securely. A password should never be logged or stored in plain text unnecessarily.
9. The Button Component
The Button component provides a simple native button for triggering an action. It is useful for straightforward actions such as submitting a form or displaying a message.
Example
import React from 'react';
import { View, Button, Alert } from 'react-native';
export default function ButtonExample() {
return (
<View>
<Button
title="Show Message"
onPress={() =>
Alert.alert('Hello', 'Button pressed successfully!')
}
/>
</View>
);
}
Important Button properties
title: the text displayed on the button.
onPress: the function called when the button is pressed.
disabled: disables the button when set to true.
accessibilityLabel: provides a more descriptive label when required.
testID: provides an identifier for automated tests.
The built-in Button offers limited styling options. Use Pressable with Text and StyleSheet when you need a customized button design.
10. The Pressable Component
Pressable is a flexible component for detecting press interactions. It can wrap text, images, cards, icons, or other elements and is useful for building custom buttons and interactive areas.
Example
import React from 'react';
import { Pressable, Text, Alert, StyleSheet } from 'react-native';
export default function PressableExample() {
return (
<Pressable
style={({ pressed }) => [
styles.button,
pressed && styles.buttonPressed
]}
onPress={() => Alert.alert('Success', 'Item selected')}
accessibilityRole="button"
accessibilityLabel="Select item"
>
<Text style={styles.buttonText}>Select Item</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
backgroundColor: '#2563EB',
padding: 14,
borderRadius: 8,
alignItems: 'center'
},
buttonPressed: {
opacity: 0.7
},
buttonText: {
color: '#FFFFFF',
fontWeight: 'bold'
}
});
Common Pressable properties
onPress: responds to a completed press.
onPressIn: responds when a press begins.
onPressOut: responds when the press is released or ends.
onLongPress: responds when the user presses and holds.
disabled: disables press interactions.
hitSlop: expands the area where a press can begin, within parent bounds.
style: can be a style object or a callback that receives press state.
Choose an accessible role and label for custom controls. A component that behaves like a button should communicate that behavior to assistive technologies.
11. The ScrollView Component
ScrollView creates a container that allows users to scroll through content. It is useful for pages with multiple sections, long forms, settings screens, and content that does not need a virtualized list.
Example
import React from 'react';
import { ScrollView, View, Text } from 'react-native';
export default function ScrollExample() {
return (
<ScrollView>
<View>
<Text>Section 1</Text>
<Text>Introduction to mobile development</Text>
</View>
<View>
<Text>Section 2</Text>
<Text>Understanding React Native components</Text>
</View>
<View>
<Text>Section 3</Text>
<Text>Building reusable interfaces</Text>
</View>
</ScrollView>
);
}
Common ScrollView properties
horizontal: enables horizontal scrolling.
showsVerticalScrollIndicator: controls the vertical scroll indicator.
showsHorizontalScrollIndicator: controls the horizontal scroll indicator.
contentContainerStyle: styles the container holding the scrollable content.
onScroll: responds to scroll events.
refreshControl: can attach pull-to-refresh functionality.
Performance consideration: A ScrollView generally renders all of its children. For very long collections of repeated items, use a virtualized list such as FlatList or SectionList.
12. The FlatList Component
FlatList is designed to display scrollable collections of data efficiently. It renders items as needed instead of requiring every item to be rendered immediately.
It is commonly used for product listings, contact lists, messages, notifications, and search results.
Example
import React from 'react';
import { FlatList, Text, View, StyleSheet } from 'react-native';
const students = [
{ id: '1', name: 'Aarav' },
{ id: '2', name: 'Priya' },
{ id: '3', name: 'Rohan' },
{ id: '4', name: 'Ananya' }
];
export default function StudentList() {
return (
<FlatList
data={students}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={styles.item}>
<Text>{item.name}</Text>
</View>
)}
/>
);
}
const styles = StyleSheet.create({
item: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#DDDDDD'
}
});
Important FlatList properties
| Property |
Purpose |
data |
Provides the collection to display. |
renderItem |
Defines how each item should be rendered. |
keyExtractor |
Provides a stable key for each item. |
ListHeaderComponent |
Displays content before the list items. |
ListFooterComponent |
Displays content after the list items. |
ListEmptyComponent |
Displays content when the list has no items. |
onEndReached |
Can trigger loading more data near the end of the list. |
refreshing |
Indicates whether pull-to-refresh is active. |
onRefresh |
Handles pull-to-refresh actions. |
numColumns |
Displays items in multiple columns when appropriate. |
FlatList best practices
- Use stable, unique keys rather than array indexes when reliable identifiers are available.
- Keep item rendering functions efficient.
- Use
getItemLayout when item dimensions are fixed and the optimization is appropriate.
- Test list behavior with realistic amounts of data.
- Use pagination or incremental loading for large remote datasets where appropriate.
13. The SectionList Component
SectionList is used when items are organized into groups with headings. For example, a contact list may group names by letter, while a schedule may group activities by day.
Example
import React from 'react';
import { SectionList, Text, View, StyleSheet } from 'react-native';
const sections = [
{
title: 'Frontend',
data: ['React', 'React Native', 'HTML']
},
{
title: 'Backend',
data: ['Node.js', 'Express', 'MySQL']
}
];
export default function CourseSections() {
return (
<SectionList
sections={sections}
keyExtractor={(item, index) => `${item}-${index}`}
renderSectionHeader={({ section }) => (
<Text style={styles.heading}>{section.title}</Text>
)}
renderItem={({ item }) => (
<View style={styles.item}>
<Text>{item}</Text>
</View>
)}
/>
);
}
const styles = StyleSheet.create({
heading: {
fontSize: 18,
fontWeight: 'bold',
padding: 12
},
item: {
padding: 12
}
});
FlatList vs SectionList
| Feature |
FlatList |
SectionList |
| Data structure |
One collection of items |
Collection divided into sections |
| Group headings |
Must be created separately or included in data |
Supports section headers directly |
| Typical example |
Product list |
Contacts grouped by letter |
| Rendering |
Virtualized list rendering |
Virtualized sectioned list rendering |
14. The Switch Component
The Switch component provides a toggle control for boolean values. It is commonly used for settings such as notifications, dark mode preferences, and location-sharing options.
Example
import React, { useState } from 'react';
import { View, Text, Switch } from 'react-native';
export default function SettingsScreen() {
const [notificationsEnabled, setNotificationsEnabled] =
useState(false);
return (
<View>
<Text>Enable notifications</Text>
<Switch
value={notificationsEnabled}
onValueChange={setNotificationsEnabled}
/>
<Text>
Status: {notificationsEnabled ? 'Enabled' : 'Disabled'}
</Text>
</View>
);
}
Important properties
value: specifies whether the switch is on or off.
onValueChange: responds to changes in the switch value.
disabled: disables user interaction.
trackColor: customizes the track color where supported.
thumbColor: customizes the thumb color.
A switch should be accompanied by a clear label so users understand what the setting controls.
15. The ActivityIndicator Component
ActivityIndicator displays a loading indicator while an operation is in progress. It is useful when loading data from an API, submitting a form, or performing another operation that takes time.
Example
import React from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
export default function LoadingScreen() {
return (
<View>
<ActivityIndicator size="large" color="#2563EB" />
<Text>Loading data...</Text>
</View>
);
}
Common properties
animating: controls whether the indicator is active.
size: controls the indicator size, subject to platform behavior.
color: specifies its color.
hidesWhenStopped: controls whether the indicator is hidden when stopped on supported platforms.
16. The Alert API
The Alert API displays a native alert dialog. It can show confirmation messages, validation feedback, warnings, and simple informational messages.
Example
import React from 'react';
import { View, Button, Alert } from 'react-native';
export default function AlertExample() {
const showAlert = () => {
Alert.alert(
'Confirmation',
'Do you want to continue?',
[
{
text: 'Cancel',
style: 'cancel'
},
{
text: 'Continue',
onPress: () => console.log('Continue selected')
}
]
);
};
return (
<View>
<Button title="Show Alert" onPress={showAlert} />
</View>
);
}
Alert behavior and available buttons may differ between Android and iOS. For long forms or complex workflows, a custom screen or modal may provide a better user experience.
17. The Modal Component
Modal displays content above the enclosing application interface. It is useful for confirmation dialogs, filters, forms, image previews, and additional details that should temporarily take focus.
Example
import React, { useState } from 'react';
import { Modal, View, Text, Button, StyleSheet } from 'react-native';
export default function ModalExample() {
const [visible, setVisible] = useState(false);
return (
<View style={styles.container}>
<Button
title="Open Modal"
onPress={() => setVisible(true)}
/>
<Modal
visible={visible}
animationType="slide"
transparent
onRequestClose={() => setVisible(false)}
>
<View style={styles.overlay}>
<View style={styles.content}>
<Text>This is a modal window.</Text>
<Button
title="Close"
onPress={() => setVisible(false)}
/>
</View>
</View>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20
},
overlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
padding: 20
},
content: {
backgroundColor: '#FFFFFF',
padding: 24,
borderRadius: 12,
gap: 12
}
});
Important Modal properties
visible: controls whether the modal is displayed.
animationType: controls the presentation animation, such as slide, fade, or none.
transparent: allows the modal background to be transparent.
onRequestClose: handles the platform's close request, including Android hardware-back behavior.
onShow: responds when the modal has been shown.
18. The StyleSheet API
StyleSheet helps organize styles into a separate object instead of placing every style directly inside JSX. This improves readability and makes repeated styles easier to maintain.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function StyledCard() {
return (
<View style={styles.card}>
<Text style={styles.title}>React Native</Text>
<Text style={styles.description}>
Build mobile applications with reusable components.
</Text>
</View>
);
}
const styles = StyleSheet.create({
card: {
padding: 16,
margin: 12,
borderRadius: 10,
backgroundColor: '#F3F4F6'
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 8
},
description: {
fontSize: 15,
lineHeight: 22
}
});
React Native styles resemble CSS in concept, but they are JavaScript objects with platform-specific behavior. Many style property names use camelCase, such as backgroundColor and fontSize.
19. Understanding Flexbox Layout
React Native uses Flexbox to arrange elements within containers. Flexbox helps create layouts that adapt to different screen sizes and orientations.
Important Flexbox properties
| Property |
Purpose |
flex |
Controls how available space is allocated. |
flexDirection |
Sets the main axis, commonly column or row. |
justifyContent |
Aligns children along the main axis. |
alignItems |
Aligns children along the cross axis. |
flexWrap |
Allows items to wrap when space is insufficient. |
gap |
Controls spacing between items where supported. |
alignSelf |
Overrides cross-axis alignment for an individual child. |
Example: Row layout
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function RowLayout() {
return (
<View style={styles.row}>
<View style={styles.box}>
<Text>One</Text>
</View>
<View style={styles.box}>
<Text>Two</Text>
</View>
<View style={styles.box}>
<Text>Three</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
padding: 16
},
box: {
padding: 16,
backgroundColor: '#DBEAFE',
borderRadius: 8
}
});
20. Safe Areas and Keyboard Handling
20.1 Safe areas
Mobile screens may contain system interface elements such as a status bar, camera cutout, or home indicator. Content should be positioned so that important elements are not obscured.
Depending on the project setup, developers may use the built-in SafeAreaView or a safe-area library such as react-native-safe-area-context. The library approach is often preferred for more comprehensive safe-area handling across screens and platforms.
Example using react-native-safe-area-context
import React from 'react';
import { Text } from 'react-native';
import {
SafeAreaProvider,
SafeAreaView
} from 'react-native-safe-area-context';
export default function SafeScreen() {
return (
<SafeAreaProvider>
<SafeAreaView>
<Text>Content inside the safe area</Text>
</SafeAreaView>
</SafeAreaProvider>
);
}
Install and configure react-native-safe-area-context according to the project's tooling before using it.
20.2 KeyboardAvoidingView
KeyboardAvoidingView can adjust its layout when the virtual keyboard appears. It is useful for login forms, registration screens, and other interfaces with text inputs.
import React from 'react';
import {
KeyboardAvoidingView,
Platform,
TextInput,
View
} from 'react-native';
export default function KeyboardExample() {
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
<View style={{ padding: 20 }}>
<TextInput
placeholder="Enter your email"
keyboardType="email-address"
autoCapitalize="none"
style={{
borderWidth: 1,
borderColor: '#CCCCCC',
padding: 12
}}
/>
</View>
</KeyboardAvoidingView>
);
}
Keyboard behavior can vary across platforms and screen layouts. Test text-entry screens on actual devices or emulators, especially when using multiline inputs, absolute positioning, or scrolling forms.
21. The RefreshControl Component
RefreshControl adds pull-to-refresh behavior to a ScrollView or a supported list component. It is commonly used to refresh feeds, notifications, and other server-driven content.
Example
import React, { useState } from 'react';
import {
ScrollView,
RefreshControl,
Text
} from 'react-native';
export default function RefreshExample() {
const [refreshing, setRefreshing] = useState(false);
const onRefresh = async () => {
setRefreshing(true);
try {
// Replace this with a real data refresh operation.
await new Promise(resolve => setTimeout(resolve, 1000));
} finally {
setRefreshing(false);
}
};
return (
<ScrollView
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
>
<Text>Pull down to refresh this content.</Text>
</ScrollView>
);
}
In a real application, replace the demonstration delay with a request to refresh the underlying data and handle any errors appropriately.
22. Choosing the Right Core Component
| Requirement |
Recommended component |
Reason |
| Group UI elements |
View |
Provides a layout container. |
| Display text |
Text |
Supports text content and styling. |
| Display a photo or logo |
Image |
Displays local and remote images. |
| Collect text |
TextInput |
Provides keyboard-based text entry. |
| Trigger a simple action |
Button |
Provides a basic native button. |
| Create a custom interactive control |
Pressable |
Supports flexible press interactions and styling. |
| Scroll through a small page of mixed content |
ScrollView |
Provides a scrollable container. |
| Display a long collection |
FlatList |
Provides virtualized list rendering. |
| Display grouped collections |
SectionList |
Supports section headers and grouped data. |
| Toggle a setting |
Switch |
Represents a boolean value. |
| Show progress |
ActivityIndicator |
Indicates an ongoing operation. |
| Display a short native message |
Alert |
Shows an alert dialog. |
| Display a temporary overlay |
Modal |
Shows content above the main interface. |
23. Practical Project: Student Directory App
Project objective: Build a simple student directory screen using React Native Core Components.
Project features
- Display the screen title using
Text.
- Use
TextInput to search for students.
- Use
FlatList to display student records.
- Use
View to organize each student card.
- Use
Pressable to select a student.
- Use
Alert to display selected student details.
- Use
ActivityIndicator if student data is loaded asynchronously.
- Show an appropriate message when no results match the search.
Complete example
import React, { useMemo, useState } from 'react';
import {
View,
Text,
TextInput,
FlatList,
Pressable,
Alert,
StyleSheet
} from 'react-native';
const students = [
{ id: '1', name: 'Aarav Sharma', course: 'React Native' },
{ id: '2', name: 'Priya Patel', course: 'Web Development' },
{ id: '3', name: 'Rohan Verma', course: 'JavaScript' },
{ id: '4', name: 'Ananya Singh', course: 'UI Development' }
];
export default function StudentDirectory() {
const [search, setSearch] = useState('');
const filteredStudents = useMemo(() => {
const query = search.trim().toLowerCase();
return students.filter(student =>
student.name.toLowerCase().includes(query)
);
}, [search]);
const renderStudent = ({ item }) => (
<Pressable
style={styles.card}
onPress={() =>
Alert.alert(item.name, `Course: ${item.course}`)
}
accessibilityRole="button"
accessibilityLabel={`View ${item.name}`}
>
<Text style={styles.name}>{item.name}</Text>
<Text>{item.course}</Text>
</Pressable>
);
return (
<View style={styles.container}>
<Text style={styles.heading}>Student Directory</Text>
<TextInput
style={styles.input}
value={search}
onChangeText={setSearch}
placeholder="Search students"
accessibilityLabel="Search students"
/>
<FlatList
data={filteredStudents}
keyExtractor={item => item.id}
renderItem={renderStudent}
ListEmptyComponent={
<Text style={styles.empty}>No students found.</Text>
}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16
},
heading: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16
},
input: {
borderWidth: 1,
borderColor: '#CCCCCC',
borderRadius: 8,
padding: 12,
marginBottom: 16
},
card: {
padding: 16,
borderRadius: 8,
backgroundColor: '#F3F4F6',
marginBottom: 10
},
name: {
fontSize: 17,
fontWeight: 'bold',
marginBottom: 4
},
empty: {
padding: 16,
textAlign: 'center'
}
});
How the project works
- The
Text component displays the directory heading.
- The
TextInput component captures the search query.
- The filtered list is calculated from the current query.
FlatList renders the matching student records.
- Each student card is wrapped in a
Pressable component.
- Pressing a student card opens an alert with the student's course.
ListEmptyComponent displays a message when no records match.
24. Common Mistakes and Troubleshooting
| Common mistake |
Why it happens |
Solution |
| Rendering plain text directly inside a View |
React Native expects text content inside a Text component. |
Wrap visible text in Text. |
| Image not appearing |
The local path may be incorrect, the remote URL may be invalid, or dimensions may be missing. |
Verify the source, network access, and image dimensions. |
| TextInput value does not update |
The controlled input may not update its state. |
Connect value and onChangeText correctly. |
| FlatList warning about keys |
Items do not have stable, unique identifiers. |
Provide an appropriate keyExtractor. |
| Large list is slow |
Too many items may be rendered at once or item rendering may be expensive. |
Use virtualized lists and optimize item rendering. |
| Button does not respond |
The callback may be missing or the button may be disabled. |
Check onPress and disabled. |
| Keyboard covers an input |
The screen layout may not account for the virtual keyboard. |
Review keyboard handling, scrolling, and platform settings. |
| Modal does not close on Android |
The modal may not handle the close request. |
Implement onRequestClose and update visibility. |
| Content is hidden by system UI |
The screen may not handle safe areas correctly. |
Use an appropriate safe-area solution. |
| Switch value does not change |
The controlled value may not be updated. |
Update state through onValueChange. |
25. Best Practices for Using Core Components
- Use semantic, descriptive component names in your custom components.
- Keep UI components small and focused on a clear responsibility.
- Use
StyleSheet.create() to organize reusable styles.
- Use
FlatList or SectionList for long collections.
- Give list items stable, unique keys.
- Provide meaningful accessibility labels and roles for interactive controls.
- Use descriptive placeholders and labels for form inputs.
- Handle loading, empty, and error states when displaying remote data.
- Test layouts on different screen sizes and both target platforms.
- Use the right component for the task rather than implementing built-in functionality from scratch.
- Check official documentation for platform-specific behavior and version changes.
26. Practice Exercises
- Create a welcome screen using
View and Text.
- Display a local logo and a remote image using
Image.
- Build a registration form with name, email, and password inputs.
- Create a custom button using
Pressable.
- Display a long article inside a
ScrollView.
- Create a product list using
FlatList.
- Group course topics into categories using
SectionList.
- Build a settings screen using
Switch.
- Display a loading indicator while simulated data loads.
- Create a confirmation dialog using
Alert.
- Build a modal containing a small contact form.
- Improve a form layout using
KeyboardAvoidingView.
- Add pull-to-refresh behavior to a scrollable list.
- Refactor a long screen into smaller reusable components.
27. Interview Questions and Answers
Q1. What are React Native Core Components?
Answer: They are built-in components that provide common user-interface functionality, including layouts, text, images, inputs, buttons, and lists.
Q2. What is the purpose of View?
Answer: View is a container used to organize other components and apply layout, styling, touch handling, and accessibility properties.
Q3. What is the difference between View and Text?
Answer: View is primarily a layout container, while Text displays and styles text content.
Q4. How do you display an image in React Native?
Answer: Use the Image component with a local resource such as require('./assets/logo.png') or a remote source such as { uri: 'https://example.com/image.png' }.
Q5. What is TextInput used for?
Answer: It allows users to enter text through the device keyboard and is commonly used in forms and search fields.
Q6. What is the difference between Button and Pressable?
Answer: Button provides a simple native button with limited styling, while Pressable supports more flexible interaction handling and custom designs.
Q7. What is ScrollView?
Answer: It is a scrollable container for content that extends beyond the visible area. It generally renders all its children.
Q8. Why is FlatList preferred for long lists?
Answer: It uses virtualized list rendering to avoid rendering every item at once, which can improve performance for large collections.
Q9. What is the difference between FlatList and SectionList?
Answer: FlatList displays a collection of items, while SectionList supports grouped items with section headers.
Q10. What does Switch do?
Answer: It provides a toggle control for a boolean value, such as enabling or disabling a setting.
Q11. What is ActivityIndicator?
Answer: It displays an indicator to show that an operation is in progress.
Q12. What is the purpose of Modal?
Answer: It displays temporary content above the main interface, such as a form, confirmation, or details panel.
Q13. Why use StyleSheet?
Answer: It organizes component styles into reusable objects, improving readability and maintainability.
Q14. What is Flexbox in React Native?
Answer: Flexbox is a layout system used to arrange, align, and distribute space among components.
Q15. How can you improve accessibility?
Answer: Use meaningful labels, appropriate accessibility roles, readable text, clear control states, and adequate touch targets.
28. Quick Revision Checklist
- Understand the role of Core Components.
- Use
View to organize layouts.
- Use
Text to display text.
- Use
Image for local and remote images.
- Manage input state with
TextInput.
- Use
Button for simple actions and Pressable for custom interactions.
- Choose
ScrollView for general scrollable content.
- Choose
FlatList and SectionList for data collections.
- Use
Switch for boolean settings.
- Use
ActivityIndicator to show loading feedback.
- Understand
Alert and Modal.
- Organize styles using
StyleSheet and Flexbox.
- Handle safe areas and keyboard behavior.
- Test accessibility and performance.
29. Official Learning Resources
30. Conclusion
React Native Core Components provide the building blocks needed to create mobile application interfaces. Components such as View, Text, Image, TextInput, and Pressable help developers create layouts and interactive controls. Components such as ScrollView, FlatList, and SectionList make it possible to display scrollable content and data collections efficiently.
By combining these components with state management, reusable custom components, Flexbox layouts, and accessibility practices, developers can build maintainable React Native applications for Android and iOS.
For further learning, explore the React Native Training Course at JustAcademy, visit the JustAcademy website, or register for a course demo.