React Native - 15 Core Components
Himanshu Aggarwal
Posted on June 3, 2024
React Native is a powerful and popular framework developed by Facebook that allows developers to build mobile applications using JavaScript and React.
One of the key advantages of React Native is its ability to create truly native applications for both iOS and Android using a single codebase. This is achieved through a set of core components provided by the framework, which bridge the gap between web development and native app development. These core components are designed to be flexible and efficient, enabling developers to create a wide variety of mobile applications with a native look and feel.
In this detailed overview, we will explore 15 of the most important core components in React Native, highlighting their functionalities, use cases, and examples to master mobile app development with React Native.
1. View
The View
component in React Native is a fundamental container component that supports various layout styles. It is the equivalent of a div
element in HTML and can be used to create and style containers for various elements.
Here’s an example of how to use the View
component:
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
function App() {
return (
<View style={styles.container}>
<Text>Hello, World!</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fffff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App;
2. Text Component
The Text
component is a basic element in React Native used to display text content on the screen. While it has some basic styling properties, you usually nest it inside other components (e.g., View
) to create more complex UIs.
import React from 'react';
import { Text, StyleSheet } from 'react-native';
const SimpleText = () => {
return (
<Text style={styles.text} numberOfLines={2} onPress={() => alert('Hello')}>
This is an example of a Text component in React Native. Tap on me!
</Text>
);
};
const styles = StyleSheet.create({
text: {
fontSize: 16,
color: 'blue',
textAlign: 'center',
margin: 10,
fontFamily: 'Arial',
},
});
export default SimpleText;
3. Text Input
TextInput
is a core component in React Native that allows the user to enter text. It is commonly used to collect user data, like emails or passwords. You can customize the appearance of TextInput
by using various props such as placeholder
, multiline
, maxLength
, and more.
Here’s a basic example of using TextInput
:
import React, { useState } from 'react';
import { TextInput, View, Button } from 'react-native';
const App = () => {
const [text, setText] = useState('');
const handleSubmit = () => {
alert('You entered: ' + text);
};
return (
<View>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => setText(text)}
value={text}
placeholder="Enter text here"
/>
<Button
onPress={handleSubmit}
title="Submit"
/>
</View>
);
};
4. Button
A Button
is a built-in React Native component used to create clickable buttons. It is a simple, customizable and easy-to-use component that captures touches and triggers an onPress
event when pressed.
Here’s a simple example of how to create a Button
in React Native:
import React from 'react';
import { Button } from 'react-native';
const MyButton = () => {
const onPressHandler = () => {
alert('Button Pressed');
};
return (
<Button
title="Click me"
color="#841584"
onPress={onPressHandler}
/>
);
};
export default MyButton;
5. Image
The Image
component is used to display images in a React Native application. It allows you to load and display local as well as remote images, providing essential props and methods for better image handling and customization.
To use the Image
component, you need to import it from ‘react-native’:
import { Image } from 'react-native';
To display a local image in the application, you have to require it in the source prop of the Image
component. Place the image file in your project directory and use the following syntax:
<Image source={require('./path/to/your/image.png')} />
To display a remote image from a URL, you need to set the source prop with a uri
object:
<Image source={{ uri: 'https://path/to/your/remote/image.png' }} />
Keep in mind that you need to define the dimensions (width and height) when using remote images:
<Image source={{ uri: 'https://path/to/remote/image.png' }} style={{ width: 200, height: 200 }} />
6. SafeAreaView
SafeAreaView
is a React Native core component that helps to adjust your app’s UI elements and layout to accommodate the notches, curved edges, or home indicator on iOS devices. It ensures that content is rendered within the visible portion of the screen.
Here is an example of using SafeAreaView
in the code:
import React from 'react';
import { SafeAreaView, StyleSheet, Text } from 'react-native';
const App = () => {
return (
<SafeAreaView style={styles.container}>
<Text>Hello World!</Text>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default App;
7. Scroll View
In React Native, the ScrollView
is a generic scrolling container used to provide a scrollable view to its child components. It is useful when you need to display scrollable content larger than the screen, such as lists, images, or text. A ScrollView
must have a bounded height in order to properly work.
Here’s a simple example of how to use the ScrollView
component in your React Native app:
import React from 'react';
import { ScrollView, Text } from 'react-native';
const MyScrollView = () => {
return (
<ScrollView>
<Text>Item 1</Text>
<Text>Item 2</Text>
<Text>Item 3</Text>
<Text>Item 4</Text>
<Text>Item 5</Text>
<Text>Item 6</Text>
</ScrollView>
);
}
export default MyScrollView;
8. FlatList
FlatList
is a React Native core component that displays a scrolling list of changing, but similarly structured, data. It is an efficient list component that makes use of a limited scrolling renderWindow
, reducing the memory footprint and creating smooth scrolling. Additionally, FlatList
supports-Headers, Footers, Pull-to-refresh, and Horizontal scrolling, among other things.
Here is a basic example demonstrating how to use the FlatList
component:
import React from 'react';
import { FlatList, View, Text } from 'react-native';
const data = [
{ id: '1', content: 'Item 1' },
{ id: '2', content: 'Item 2' },
{ id: '3', content: 'Item 3' },
// ...
];
const renderItem = ({ item }) => (
<View>
<Text>{item.content}</Text>
</View>
);
const MyFlatList = () => (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
);
export default MyFlatList;
9. Switch
A Switch
is a core component in React Native used to implement a “toggle” or “on-off” input. It provides a UI for the user to switch between two different states, typically true or false. The primary use case is to enable or disable a feature or setting within an application.
Switch
component has a boolean value
prop (true for on, false for off) and an onValueChange
event handler, which is triggered whenever the user toggles the switch.
Here’s an example of how to use Switch
in a React Native application:
import React, {useState} from 'react';
import {View, Switch, Text} from 'react-native';
const App = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View>
<Text>Enable Feature:</Text>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
);
};
export default App;
10. Modal
A Modal
is a component that displays content on top of the current view, creating an overlay that can be used for various purposes, such as displaying additional information, confirmation messages, or a selection menu.
import React, {useState} from 'react';
import {Modal, Text, TouchableHighlight, View, Alert} from 'react-native';
const App = () => {
const [modalVisible, setModalVisible] = useState(false);
return (
<View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
setModalVisible(!modalVisible);
}}>
<View>
<View>
<Text>Hello, I am a Modal!</Text>
<TouchableHighlight
onPress={() => {
setModalVisible(!modalVisible);
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<TouchableHighlight
onPress={() => {
setModalVisible(true);
}}>
<Text>Show Modal</Text>
</TouchableHighlight>
</View>
);
};
export default App;
11. Pressable
Pressable
is a core component in React Native that makes any view respond properly to touch or press events. It provides a wide range of event handlers for managing user interactions, such as onPress
, onPressIn
, onPressOut
, and onLongPress
. With Pressable, you can create custom buttons, cards, or any touchable elements within your app.
import React from 'react';
import { Pressable, Text, StyleSheet } from 'react-native';
export default function CustomButton() {
return (
<Pressable
onPress={() => console.log('Pressed!')}
style={({ pressed }) => [
styles.button,
pressed ? styles.pressedButton : styles.normalButton,
]}
>
<Text style={styles.buttonText}>Press me</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
padding: 10,
borderRadius: 5,
},
normalButton: {
backgroundColor: 'blue',
},
pressedButton: {
backgroundColor: 'darkblue',
},
buttonText: {
color: 'white',
textAlign: 'center',
},
});
12. TouchableOpacity
In React Native, Touchable components are used to handle user interactions like taps, long presses, and double-taps on the appropriate elements.
TouchableOpacity
is The opacity of the wrapped view is decreased when it’s active.
import { TouchableOpacity } from 'react-native';
<TouchableOpacity
onPress={() => {
alert('Tapped!');
}}
>
<Text>Tap me</Text>
</TouchableOpacity>
13. Activity Indicator
The ActivityIndicator
is a core component in React Native that provides a simple visual indication of some ongoing activity or loading state within your application. It shows a spinning animation, which gives the user feedback that something is happening in the background. This component is particularly useful when fetching data from an external source, like a server, or while performing time-consuming operations.
To use the ActivityIndicator component, simply import it from ‘react-native’, and add it to your component tree. You can customize the appearance and behavior of the ActivityIndicator
by providing various optional props, such as animating, color, and size.
Below is an example of how to use the ActivityIndicator
component within a functional React component:
import React from 'react';
import { ActivityIndicator, View, Text } from 'react-native';
const LoadingScreen = () => (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Loading, please wait...</Text>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
export default LoadingScreen;
14. StatusBar
The StatusBar
component is used to control the appearance of the status bar on the top of the screen. It may strike as a bit unusual since, unlike other React Native components, it doesn’t render any visible content. Instead, it sets some native properties that can help customize the look of status bars on Android, iOS, or other platforms.
To use the StatusBar
component, you need to import it from ‘react-native’ and use it in your React component. Here’s an example:
import React from 'react';
import { View, StatusBar } from 'react-native';
const App = () => {
return (
<View>
<StatusBar barStyle="dark-content" backgroundColor="#F0F0F0" />
{/* Your other components */}
</View>
);
};
export default App;
15. SectionList
SectionList
is a component used to render sections and headers in a scroll view. It helps to manage and optimize a large list of items divided into categories. It is one of the List View
components provided by React Native along with FlatList
.
The key difference between SectionList
and FlatList
is that SectionList
separates data items into sections, with headers.
Here’s an example of how to use a SectionList
in your app:
import React, {Component} from 'react';
import {SectionList, StyleSheet, Text, View, SafeAreaView} from 'react-native';
export default class App extends Component {
render() {
return (
<SafeAreaView style={styles.container}>
<SectionList
sections={[
{
title: 'Section 1',
data: ['Item 1.1', 'Item 1.2', 'Item 1.3'],
},
{
title: 'Section 2',
data: ['Item 2.1', 'Item 2.2', 'Item 2.3'],
},
]}
renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader={({section}) => (
<Text style={styles.sectionHeader}>{section.title}</Text>
)}
keyExtractor={(item, index) => String(index)}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingRight: 10,
paddingLeft: 10,
},
sectionHeader: {
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'lightgrey',
padding: 5,
},
item: {
fontSize: 16,
padding: 10,
borderBottomWidth: 1,
borderBottomColor: 'black',
},
});
Posted on June 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.