React Native: Set different colors on Top and Bottom in SafeAreaView component

React Native|SEPTEMBER 19, 2024|2 VIEWS
Sometimes, on SafeAreaView component, we need using a different color on Top and another on Bottom

Sometimes, on SafeAreaView component, we need using a different color on Top and another on Bottom

Today I will guide you some ways to do that

Let’s get started with the code!

Create React Native App

react-native init SafeAreaViewApp

Implementing on the main file

Open the file App.tsx file and change the content with:

import React, { Fragment } from "react";
import { StyleSheet, Text, View, SafeAreaView } from "react-native";

const App = () => {
  return (
    <Fragment>
      <SafeAreaView style={{ flex: 0, backgroundColor: "red" }} />
      <SafeAreaView style={{ flex: 1, backgroundColor: "blue" }}>
        <View style={styles.container}>
          <Text style={styles.welcome}>Welcome to React Native!</Text>
        </View>
      </SafeAreaView>
    </Fragment>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#FFFFFF",
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
  },
});

export default App;

So... that's it!

Another way, if you are using react-native-safe-area-context

import React, { Fragment } from "react";
import { StyleSheet, Text, View } from "react-native";
import {
  SafeAreaProvider,
  useSafeAreaInsets,
} from "react-native-safe-area-context";

const App = () => {
  return (
    <SafeAreaProvider>
      <AppContent />
    </SafeAreaProvider>
  );
};

const AppContent = () => {
  const insets = useSafeAreaInsets();
  return (
    <Fragment>
      <View style={{ height: insets.top, backgroundColor: "red" }} />
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
      </View>
      <View style={{ height: insets.bottom, backgroundColor: "blue" }} />
    </Fragment>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#FFFFFF",
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
  },
});

export default App;