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

javascript
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

javascript
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.create can help you catch errors in your styles early on.

Example: Using StyleSheet

javascript
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.

javascript
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.

javascript
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

  1. Installation:

    bash
    npm install react-native-vector-icons
  2. Linking (for Android):
    Add the following line to your android/app/build.gradle file:

    groovy
    apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

Example: Using an Icon

javascript
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

  1. Installation:

    bash
    npm install react-native-safe-area-context
  2. Wrap your app in SafeAreaProvider:
    This should be done at the root of your application, typically in your App.js file.

    javascript
    import { 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.

javascript
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

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:

  1. The root element of the component must be a SafeAreaView from react-native-safe-area-context.
  2. Inside the SafeAreaView, create a container View that will act as the profile card.
  3. Inside the card View, add an Image component. It should display a user avatar from the following URL: https://reactnative.dev/img/tiny_logo.png.
  4. Below the Image, add two Text components: one for the user's name ("React Native Developer") and one for a short bio ("Building beautiful cross-platform apps.").
  5. All styles must be defined using StyleSheet.create. Do not use any inline styles.
  6. Apply the following styles using the StyleSheet object you create:
    • Safe Area Container (safeArea):
      • flex: 1
      • justifyContent: 'center'
      • alignItems: 'center'
    • Card Container (card):
      • padding: 20
      • backgroundColor: '#f0f0f0'
      • borderRadius: 10
      • alignItems: 'center'
      • width: '80%'
    • Image (avatar):
      • width: 100
      • height: 100
      • borderRadius: 50
      • marginBottom: 15
    • Name Text (name):
      • fontSize: 20
      • fontWeight: 'bold'
    • Bio Text (bio):
      • fontSize: 14
      • color: '#666'
      • marginTop: 5

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.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.