Core Components & Styling
7 min read
Core Components & Styling: The Building Blocks of Your React Native App 🎨
Welcome to the foundational chapter of your React Native journey! Here, we'll explore the essential building blocks that will form the structure, style, and visual appeal of your mobile applications. Think of these core components as the Lego bricks of your app – simple on their own, but incredibly powerful when combined.
View & Text: The Foundation of React Native 🧱
At the very heart of any React Native application, you'll find two fundamental components: View and Text. Understanding these is like learning the alphabet before you can write a novel.
The Problem: How do we structure content and display text in a mobile app? In web development, we have divs, spans, paragraphs, and headings. What are the equivalents in React Native?
The Solution: View and Text are your go-to components for these exact purposes.
What is a View?
A View is the most fundamental component for building a user interface. It's a container that supports layout with flexbox, styling, some touch handling, and accessibility controls. Think of it as a <div> in the world of web development. It's a simple, yet powerful, box that can hold other components.
You can nest View components inside each other to create complex layouts. This is especially useful for structuring your UI with parent and child containers that might have different styling or layout properties.
Example: A Simple View
import React from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Hello from inside a View!</Text>
</View>
);
};
export default MyComponent;In this example, the View acts as a container that centers its child, the Text component, both horizontally and vertically.
What is a Text?
The Text component, as the name suggests, is used for displaying text. Unlike in web development where you can place text directly inside a <div>, in React Native, any text you want to display must be wrapped within a Text component.
Example: Displaying Text
import React from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => {
return (
<View style={{ flex: 1, paddingTop: 50, paddingHorizontal: 20 }}>
<Text>This is a line of text.</Text>
<Text style={{ fontWeight: 'bold' }}>This is some bold text.</Text>
</View>
);
};
export default MyComponent;Notice how we can style the Text component directly. We'll dive deeper into styling in the next section.
Fun Fact: Under the hood, a React Native <View> gets translated into a native UIView on iOS and a android.view.View on Android. This is why React Native apps have a truly native look and feel!
StyleSheet: Styling Your App the Native Way 💅
Now that you know how to structure your app with View and Text, let's make it look good!
The Problem: How do we apply styles to our components in a way that is both organized and performant? We could use inline styles, but that can get messy and inefficient for larger applications.
The Solution: The StyleSheet API is React Native's answer to CSS. It allows you to define your styles in a separate object, promoting code reusability and better organization.
Why Use StyleSheet?
- Performance: By creating a
StyleSheet, you send the style information over the bridge to the native side only once. This can lead to performance improvements compared to creating a new style object every time a component renders. - Organization: It keeps your styling logic separate from your component's rendering logic, making your code cleaner and easier to read.
- Validation:
StyleSheet.createcan help you catch errors in your styles early on.
Example: Using StyleSheet
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const MyComponent = () => {
return (
<View style={styles.container}>
<Text style={styles.title}>Hello, StyleSheet!</Text>
<Text style={styles.subtitle}>This is styled using StyleSheet.</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#333',
},
subtitle: {
fontSize: 16,
color: 'gray',
},
});
export default MyComponent;In this example, we've defined all our styles in a StyleSheet object and then referenced them in our components. This is the industry standard for styling in React Native.
Interesting Tidbit: React Native uses Flexbox for layout, which is a powerful tool for creating responsive designs that work on different screen sizes.
Images & Icons: Bringing Visuals to Life 🖼️
Text and boxes are great, but a picture is worth a thousand words. Let's add some visual flair to our app.
The Problem: How do we display images and icons in our application?
The Solution: The Image component and third-party libraries for icons are the way to go.
Displaying Images
The Image component can display images from various sources, including local files and network URLs.
Example: Displaying a Local Image
To display a local image, you need to require it. The bundler will then package this image with your app.
import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
const MyComponent = () => {
return (
<View style={styles.container}>
<Image
style={styles.logo}
source={require('./assets/logo.png')}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logo: {
width: 100,
height: 100,
},
});
export default MyComponent;Example: Displaying a Network Image
For network images, you provide a URI in the source prop. You must also specify the dimensions of the image.
import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
const MyComponent = () => {
return (
<View style={styles.container}>
<Image
style={styles.image}
source={{ uri: 'https://reactnative.dev/img/tiny_logo.png' }}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
image: {
width: 50,
height: 50,
},
});
export default MyComponent;Adding Icons
While you can use images for icons, a more common and scalable approach is to use a vector icon library. react-native-vector-icons is a popular choice that provides a wide range of icon sets.
Getting Started with react-native-vector-icons
Installation:
bashnpm install react-native-vector-iconsLinking (for Android):
Add the following line to yourandroid/app/build.gradlefile:groovyapply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
Example: Using an Icon
import React from 'react';
import { View, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
const MyComponent = () => {
return (
<View style={styles.container}>
<Icon name="rocket" size={30} color="#900" />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default MyComponent;SafeAreaView: Respecting Device Notches & Bezels 📱
Modern phones have all sorts of notches, cutouts, and home indicators. We need to make sure our app's content doesn't get hidden behind them.
The Problem: How do we ensure our app's UI is not obscured by the physical features of the device, like the notch on an iPhone or the status bar on Android?
The Solution: The SafeAreaView component is designed to solve this exact problem. It automatically adds padding to its content to avoid overlapping with these system UI elements.
Why react-native-safe-area-context is the Industry Standard
While React Native has a built-in SafeAreaView, it only works on iOS 11+ and has some known issues with animations. The community has embraced react-native-safe-area-context as a more robust and cross-platform solution.
Getting Started
Installation:
bashnpm install react-native-safe-area-contextWrap your app in
SafeAreaProvider:
This should be done at the root of your application, typically in yourApp.jsfile.javascriptimport { SafeAreaProvider } from 'react-native-safe-area-context'; function App() { return ( <SafeAreaProvider> {/* Your app's navigation and screens go here */} </SafeAreaProvider> ); }
Example: Using SafeAreaView
Now, you can use the SafeAreaView from this library in your screens.
import React from 'react';
import { Text, StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
const MyScreen = () => {
return (
<SafeAreaView style={styles.container}>
<Text>This content is within the safe area.</Text>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default MyScreen;Pro-Tip: Sometimes you only need to apply padding to specific sides (e.g., just the top). The edges prop on SafeAreaView allows you to do this for more granular control.
Further Reading & Resources
- React Native Core Components: https://reactnative.dev/docs/intro-react-native-components
- React Native StyleSheet API: https://reactnative.dev/docs/stylesheet
- Image Component: https://reactnative.dev/docs/image
- react-native-vector-icons: https://github.com/oblador/react-native-vector-icons
- react-native-safe-area-context: https://github.com/th3rdwave/react-native-safe-area-context
Challenge
Challenge: Build a Profile Card Component
Your task is to build a ProfileCard component using React Native's core components. You must use StyleSheet.create for all styling and ensure the layout is safe from device notches.
Requirements:
- The root element of the component must be a
SafeAreaViewfromreact-native-safe-area-context. - Inside the
SafeAreaView, create a containerViewthat will act as the profile card. - Inside the card
View, add anImagecomponent. It should display a user avatar from the following URL:https://reactnative.dev/img/tiny_logo.png. - Below the
Image, add twoTextcomponents: one for the user's name ("React Native Developer") and one for a short bio ("Building beautiful cross-platform apps."). - All styles must be defined using
StyleSheet.create. Do not use any inline styles. - Apply the following styles using the
StyleSheetobject you create:- Safe Area Container (
safeArea):flex: 1justifyContent: 'center'alignItems: 'center'
- Card Container (
card):padding: 20backgroundColor: '#f0f0f0'borderRadius: 10alignItems: 'center'width: '80%'
- Image (
avatar):width: 100height: 100borderRadius: 50marginBottom: 15
- Name Text (
name):fontSize: 20fontWeight: 'bold'
- Bio Text (
bio):fontSize: 14color: '#666'marginTop: 5
- Safe Area Container (
Expected result
The final rendered output should be a single profile card centered both vertically and horizontally on the screen.
- The card has a light grey background (
#f0f0f0) with rounded corners and occupies 80% of the screen's width. - At the top of the card, a circular image (100x100 pixels) of the React logo is displayed.
- Below the image, the text "React Native Developer" appears in a bold, 20px font.
- Directly under the name, the bio text "Building beautiful cross-platform apps." is displayed in a smaller, grey font.
- The entire layout is contained within a
SafeAreaView, ensuring that no part of the card is obscured by a device's status bar or notch.