Components of React Native
Components in React are the basic building blocks from which you build applications. Each component has its own logic and appearance, so you can easily create, modify and use them repeatedly in different places in the application. They can be simple (e.g. displaying text) or complex (e.g. containing many other components). Components make the code more organized and easier to understand and develop. In the following article, we introduce the basic components and APIs available in React Native, which enable developers to quickly and efficiently create user interfaces in mobile applications.
React Native offers a set of so-called Core Components, which are the basic building blocks of mobile applications. These components are organized into different categories, such as core components, UI components, list views, Android and iOS specific components.
1. The most important basic components in React Native
View
It serves as a container for other components. It can be used to group components and create layout structures, example:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<View style={styles.box}>
<Text style={styles.text}>Hello from inside the View!</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 150,
height: 150,
backgroundColor: 'lightblue',
justifyContent: 'center',
alignItems: 'center',
},
text: {
color: 'white',
},
});
export default App;
Text
The Text component is used to display text. It can be styled using StyleSheet
, below is an example:
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, this is a Text component!</Text>
<Text style={styles.boldText}>Another Text component with bold styling.</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 20,
},
boldText: {
fontSize: 20,
fontWeight: 'bold',
},
});
export default App;
Image
The Image component is used to display images in the application.
import React from 'react';
import { Image, View, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Image
source={{ uri: 'https://reactnative.dev/img/tiny_logo.png' }}
style={styles.image}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
image: {
width: 100,
height: 100,
},
});
export default App;
TextInput
The TextInput component is used to allow the user to type text. An example of the TextInput component below:
import React, { useState } from 'react';
import { TextInput, View, Text, StyleSheet } from 'react-native';
const App = () => {
const [text, setText] = useState('');
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Enter some text"
value={text}
onChangeText={(newText) => setText(newText)}
/>
<Text>You typed: {text}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
padding: 10,
width: '80%',
marginBottom: 20,
},
});
export default App;
Scrollview
The ScrollView component allows you to scroll through content, especially if there is more content than the screen can accommodate.
Example:
import React from 'react';
import { ScrollView, View, Text, StyleSheet } from 'react-native';
const App = () => {
return (
<ScrollView style={styles.scrollView}>
{Array.from({ length: 20 }, (_, i) => (
<View key={i} style={styles.item}>
<Text>Item {i + 1}</Text>
</View>
))}
</ScrollView>
);
};
const styles = StyleSheet.create({
scrollView: {
marginVertical: 20,
},
item: {
padding: 20,
marginVertical: 10,
backgroundColor: 'lightgray',
alignItems: 'center',
},
});
export default App;
StyleSheet
The StyleSheet component is used to define styles in React Native, which can then be assigned to components.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.title}>Hello, StyleSheet Example!</Text>
<Text style={styles.subtitle}>This is how you define reusable styles in React Native.</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 10,
},
subtitle: {
fontSize: 16,
color: 'gray',
},
});
export default App;
UI components
In the following section, we introduce some important UI components that are available in React Native and can be used to build interactive and aesthetically pleasing user interfaces.
CustomButton
A button that the user can press to trigger a specific action (e.g. save data, move to the next screen, etc.). Below is an example of such a component:
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
// CustomButton - Przycisk UI
const CustomButton = ({ title, onPress }) => {
return (
<TouchableOpacity style={styles.button} onPress={onPress}>
<Text style={styles.buttonText}>{title}</Text>
</TouchableOpacity>
);
};
// Stylizacje przycisku
const styles = StyleSheet.create({
button: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginVertical: 10,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
export default CustomButton;
// Przykład użycia komponentu CustomButton
// import CustomButton from './CustomButton';
//
// const App = () => {
// return (
// <CustomButton
// title="Kliknij mnie!"
// onPress={() => alert('Przycisk został kliknięty!')}
// />
// );
// };
Card
Card is a component that displays information in a clear and visually appealing way. Most often it consists of a title, description and sometimes additional elements, such as an image or buttons. It is used, for example, to present a single product, an article, or a list item.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
// Card - Karta UI
const Card = ({ title, description }) => {
return (
<View style={styles.card}>
<Text style={styles.cardTitle}>{title}</Text>
<Text style={styles.cardDescription}>{description}</Text>
</View>
);
};
// Stylizacje komponentu Card
const styles = StyleSheet.create({
card: {
backgroundColor: '#FFFFFF',
padding: 15,
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 5,
marginVertical: 10,
},
cardTitle: {
fontSize: 18,
fontWeight: 'bold',
},
cardDescription: {
fontSize: 14,
color: '#777777',
marginTop: 5,
},
});
export default Card;
// Przykład użycia komponentu Card
// import Card from './Card';
//
// const App = () => {
// return (
// <Card
// title="Tytuł Karty"
// description="This is a sample description for this card."
// />
// );
// };
Modal
The Modal component is used to display content that catches the user’s attention, such as messages or forms. A modal typically displays additional information against the background of the current view and requires user interaction to continue.
import React, { useState } from 'react';
import { View, Text, Modal, TouchableOpacity, StyleSheet } from 'react-native';
// CustomModal - Komponent Modal
const CustomModal = ({ visible, onClose, title, content }) => {
return (
<Modal
transparent={true}
animationType="slide"
visible={visible}
onRequestClose={onClose}
>
<View style={styles.modalOverlay}>
<View style={styles.modalContent}>
<Text style={styles.modalTitle}>{title}</Text>
<Text style={styles.modalText}>{content}</Text>
<TouchableOpacity style={styles.closeButton} onPress={onClose}>
<Text style={styles.closeButtonText}>Zamknij</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
);
};
// Stylizacje komponentu Modal
const styles = StyleSheet.create({
modalOverlay: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
},
modalContent: {
width: 300,
backgroundColor: '#FFF',
padding: 20,
borderRadius: 10,
alignItems: 'center',
},
modalTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 10,
},
modalText: {
fontSize: 16,
color: '#777',
textAlign: 'center',
marginBottom: 20,
},
closeButton: {
backgroundColor: '#4CAF50',
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 5,
},
closeButtonText: {
color: '#FFF',
fontSize: 16,
},
});
// Przykład użycia komponentu CustomModal
const App = () => {
const [isModalVisible, setIsModalVisible] = useState(false);
const toggleModal = () => {
setIsModalVisible(!isModalVisible);
};
return (
<View style={styles.appContainer}>
<TouchableOpacity style={styles.openButton} onPress={toggleModal}>
<Text style={styles.openButtonText}>Otwórz Modal</Text>
</TouchableOpacity>
<CustomModal
visible={isModalVisible}
onClose={toggleModal}
title="Przykładowy Modal"
content="To jest przykładowa treść modala. Możesz zamknąć modal, naciskając przycisk poniżej."
/>
</View>
);
};
// Stylizacje dla przykładu użycia
const stylesApp = StyleSheet.create({
appContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
openButton: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
},
openButtonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
export default App;
Switch
Switch is a native React Native component that is used to render a Boolean
switch, representing a value of type boolean
(true
or false
). It is usually used to toggle some option on or off.
Below you will find sample code for the Switch component :
import React, { useState } from 'react';
import { View, Text, Switch, StyleSheet } from 'react-native';
// Komponent CustomSwitch
const CustomSwitch = ({ label, value, onValueChange }) => {
return (
<View style={styles.switchContainer}>
<Text style={styles.switchLabel}>{label}</Text>
<Switch
value={value} // Kontrolowane przez stan rodzica
onValueChange={onValueChange} // Callback, który zmienia stan
thumbColor={value ? '#4CAF50' : '#f4f3f4'}
trackColor={{ false: '#767577', true: '#81b0ff' }}
/>
</View>
);
};
// Przykład użycia komponentu CustomSwitch
const App = () => {
// Zarządzanie stanem przełącznika - kontrolowanie wartości `value` Switcha
const [isEnabled, setIsEnabled] = useState(false);
// Funkcja callback do zmiany stanu
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View style={stylesApp.container}>
<CustomSwitch
label="Włącz Tryb Ciemny"
value={isEnabled} // Wartość przełącznika, przekazywana jako prop
onValueChange={toggleSwitch} // Callback, który zmienia stan, aby `Switch` zaktualizował wartość
/>
</View>
);
};
// Stylizacje komponentów
const styles = StyleSheet.create({
switchContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginVertical: 10,
paddingHorizontal: 20,
},
switchLabel: {
fontSize: 16,
color: '#333',
},
});
const stylesApp = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
export default App;
Components for Android in React Native
React Native offers various Android-specific tools that allow for a more native user experience and integration with operating system features. Below are components and APIs that are Android-specific, meaning they help you build applications dedicated to this platform.
BackHandler
The BackHandler component is used to detect “back” button presses on an Android device. It is used to control what happens when the user tries to exit the app or return to the previous screen.
BackHandler component code example:
import React, { useEffect } from 'react';
import { View, Text, StyleSheet, BackHandler, Alert } from 'react-native';
// BackHandler Example
const BackHandlerExample = () => {
useEffect(() => {
// Funkcja obsługująca naciśnięcie przycisku "wstecz"
const backAction = () => {
Alert.alert("Uwaga!", "Czy na pewno chcesz wyjść?", [
{
text: "Nie",
onPress: () => null,
style: "cancel",
},
{ text: "Tak", onPress: () => BackHandler.exitApp() },
]);
return true; // Zatrzymuje domyślne działanie przycisku "wstecz"
};
// Dodanie listenera do naciśnięcia przycisku "wstecz"
const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backAction
);
// Czyszczenie listenera przy odmontowaniu komponentu
return () => backHandler.remove();
}, []);
return (
<View style={styles.container}>
<Text style={styles.infoText}>
Naciśnij przycisk "wstecz", aby wyświetlić komunikat.
</Text>
</View>
);
};
// Stylizacje komponentu BackHandlerExample
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
infoText: {
fontSize: 16,
textAlign: 'center',
marginHorizontal: 20,
},
});
export default BackHandlerExample;
DrawerLayoutAndroid
A component that allows you to render a side drawer view (Drawer Layout) on Android. Drawer is a slide-out menu that usually contains navigation options. It is often used to implement an app’s navigation menu. DrawerLayoutAndroid is specific to Android, but similar effects can be achieved using multiplatform libraries like React Navigation.
Example:
import React, { useRef } from 'react';
import { View, Text, StyleSheet, DrawerLayoutAndroid, TouchableOpacity } from 'react-native';
const DrawerLayoutExample = () => {
// Użycie hooka useRef, aby uzyskać referencję do DrawerLayoutAndroid
const drawer = useRef(null);
// Widok zawartości szuflady
const renderDrawerContent = () => (
<View style={styles.drawerContainer}>
<Text style={styles.drawerHeader}>Menu Nawigacyjne</Text>
<TouchableOpacity style={styles.drawerItem} onPress={() => drawer.current.closeDrawer()}>
<Text style={styles.drawerItemText}>Strona Główna</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.drawerItem} onPress={() => drawer.current.closeDrawer()}>
<Text style={styles.drawerItemText}>Profil</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.drawerItem} onPress={() => drawer.current.closeDrawer()}>
<Text style={styles.drawerItemText}>Ustawienia</Text>
</TouchableOpacity>
</View>
);
return (
<DrawerLayoutAndroid
ref={drawer}
drawerWidth={250}
drawerPosition="left"
renderNavigationView={renderDrawerContent}
>
<View style={styles.container}>
<TouchableOpacity onPress={() => drawer.current.openDrawer()} style={styles.openDrawerButton}>
<Text style={styles.openDrawerText}>Otwórz Menu</Text>
</TouchableOpacity>
<Text style={styles.mainText}>To jest główny widok aplikacji.</Text>
</View>
</DrawerLayoutAndroid>
);
};
// Stylizacje komponentów
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
openDrawerButton: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
marginBottom: 20,
},
openDrawerText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
mainText: {
fontSize: 18,
textAlign: 'center',
color: '#333',
},
drawerContainer: {
flex: 1,
backgroundColor: '#FFF',
padding: 16,
},
drawerHeader: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
drawerItem: {
marginVertical: 10,
},
drawerItemText: {
fontSize: 16,
color: '#000',
},
});
export default DrawerLayoutExample;
PermissionsAndroid
The PermissionsAndroid component allows you to check and ask users for access to device resources, such as the camera, location or memory. This is crucial to ensure that the application has the right permissions to run on Android.
Example:
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, PermissionsAndroid, Alert } from 'react-native';
const PermissionsExample = () => {
const [locationPermission, setLocationPermission] = useState(false);
// Funkcja do proszenia użytkownika o uprawnienia lokalizacji
const requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Uprawnienia Lokalizacji',
message:
'Aplikacja potrzebuje dostępu do Twojej lokalizacji, aby świadczyć lepsze usługi.',
buttonNeutral: 'Zapytaj później',
buttonNegative: 'Anuluj',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
setLocationPermission(true);
Alert.alert("Uprawnienia przyznane", "Masz teraz dostęp do lokalizacji.");
} else {
setLocationPermission(false);
Alert.alert("Uprawnienia odrzucone", "Nie przyznano dostępu do lokalizacji.");
}
} catch (err) {
console.warn(err);
}
};
return (
<View style={styles.container}>
<Text style={styles.infoText}>
{locationPermission
? "Uprawnienia lokalizacji są przyznane."
: "Uprawnienia lokalizacji nie są przyznane."}
</Text>
<TouchableOpacity style={styles.permissionButton} onPress={requestLocationPermission}>
<Text style={styles.buttonText}>Poproś o dostęp do lokalizacji</Text>
</TouchableOpacity>
</View>
);
};
// Stylizacje komponentu PermissionsExample
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding: 20,
},
infoText: {
fontSize: 18,
textAlign: 'center',
marginBottom: 20,
},
permissionButton: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
export default PermissionsExample;
ToastAndroid
The ToastAndroid component allows you to create native Toast notifications in Android. A toast is a small, non-intrusive notification that appears for a short time at the bottom of the screen and automatically disappears.
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ToastAndroid } from 'react-native';
const ToastExample = () => {
// Funkcja do wyświetlania Toast
const showToast = () => {
ToastAndroid.show("To jest wiadomość Toast", ToastAndroid.SHORT);
};
const showToastWithGravity = () => {
ToastAndroid.showWithGravity(
"To jest Toast z grawitacją!",
ToastAndroid.LONG,
ToastAndroid.CENTER
);
};
const showToastWithGravityAndOffset = () => {
ToastAndroid.showWithGravityAndOffset(
"Toast z grawitacją i przesunięciem!",
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
0, // Przesunięcie w poziomie
50 // Przesunięcie w pionie
);
};
return (
<View style={styles.container}>
<Text style={styles.header}>Przykłady ToastAndroid</Text>
<TouchableOpacity style={styles.button} onPress={showToast}>
<Text style={styles.buttonText}>Pokaż Toast (krótki)</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={showToastWithGravity}>
<Text style={styles.buttonText}>Pokaż Toast z grawitacją</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={showToastWithGravityAndOffset}>
<Text style={styles.buttonText}>Pokaż Toast z przesunięciem</Text>
</TouchableOpacity>
</View>
);
};
// Stylizacje komponentu ToastExample
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
header: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
button: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
marginVertical: 10,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
export default ToastExample;
iOS-specific components in React Native
The iOS-specific components in React Native are used to provide more native integration with the iOS user interface. With the development of React Native, some iOS-dedicated components have been rendered obsolete and have been replaced by cross-platform components such as: ActionSheetIOS.
ActionSheetIOS.
ActionSheetIOS is an API component used to display actions for the user to choose from. It works in the form of a fly-out sheet from the bottom of the screen, containing a list of options that the user can choose from, such as “Cancel” or “Delete.” It can be used to offer the user a choice from several options. A typical use case is asking the user what they want to do with an item.
Below is an example of the ActionSheetIOS component:
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ActionSheetIOS } from 'react-native';
const ActionSheetExample = () => {
// ActionSheet opening function
const showActionSheet = () => {
ActionSheetIOS.showActionSheetWithOptions(
{
options: ["Cancel", "Option 1", "Option 2", "Delete"],
destructiveButtonIndex: 3, // Destructive button index
cancelButtonIndex: 0, // Cancel button index
title: "Select an option",
message: "Select one of the available options below:",
},
(buttonIndex) => {
// Handle the user's button selection
if (buttonIndex === 0) {
console.log("User cancelled the action");
} else if (buttonIndex === 1) {
console.log("Selected Option 1");
} else if (buttonIndex === 2) {
console.log("Selected Option 2");
} else if (buttonIndex === 3) {
console.log("Delete selected");
}
}
);
};
return (
<View style={styles.container}>
<Text style={styles.header}>Example of using ActionSheetIOS</Text>
<TouchableOpacity style={styles.button} onPress={showActionSheet}>
<Text style={styles.buttonText}>Show ActionSheet</Text>
</TouchableOpacity>
</View>
);
};
// ActionSheetExample component styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding: 20,
},
header: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
button: {
backgroundColor: '#4CAF50',
padding: 15,
borderRadius: 8,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
export default ActionSheetExample;