Open In App

How to center a View component on screen ?

The View Component is the basic building block for creating the user interface. It can map directly to the native view of different platforms, like UIView, <div>, android.view, etc. The View component can consist of nested View components as well as other native components (children).

Approach: To center a View component on the screen, we can use two approaches: 



Example: Let’s see how to center the View component on the screen using the above approaches through examples:

Project Structure: The project directory should look like the following:

Example 1: Using flexbox
We will use a single View Component with nested Text components as its children. To center our View component, we will use the flex property, which is set to 1, along with the justifyAlign and alignItems properties (both set to center since the View component is required to be centered on the screen).




import React from "react";
import { View, Text, StyleSheet } from "react-native";
  
export default function App() {
  return (
    <View style={styles.centered}>
      <Text style={styles.title}>Center a View Component</Text>
      <Text style={styles.subtitle}>Using Flexbox</Text>
    </View>
  );
}
  
const styles = StyleSheet.create({
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#ffc2c2",
  },
  title: {
    fontSize: 18,
    marginVertical: 2,
  },
  subtitle: {
    fontSize: 14,
    color: "#888",
  },
});

Step to run the application: Start the server by using the following command:

expo start

Output:

Example 2: Using CSS position property
We will use a single View Component with nested Text components as its children. To center our View component, we will use the position property, which is set to absolute. We will also use the top, bottom, left and right values and set them to 0 (since the View component is required to be centered on the screen) As before, we will also require the justifyAlign and alignItems properties with their values set as center.




import React from "react";
import { View, Text, StyleSheet } from "react-native";
  
export default function App() {
  return (
    <View style={styles.centered}>
      <Text style={styles.title}>Center a View Component</Text>
      <Text style={styles.subtitle}>Using CSS Position property</Text>
    </View>
  );
}
  
const styles = StyleSheet.create({
  centered: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#ffc2c2",
  },
  title: {
    fontSize: 18,
    marginVertical: 2,
  },
  subtitle: {
    fontSize: 14,
    color: "#888",
  },
});

Step to run the application: Start the server by using the following command:

expo start

Output:


Article Tags :