Leon Chaewon Kong's dev blog

React Native - iOS Set Different Colors to Top and Bottom of SafeAreaView

SafeAreaView only works on iOS devices with version 11 or later. It automatically applies paddings to its nested child views. It considers physical limitation of screen differ from devices to devices.

Set different colors to top and bottom of SafeAreaView

When creating app, sometimes it is needed to apply different colors to top and bottom SafeAreaView padding. Let’s find it out how.

Requirements

react >= 16.2.0

We are gonna use Fragment imported from React. Fragment is available in React version above 16.2.0.

Default usage of SafeAreaView will like:

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

export default class App extends Component {
  render() {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1, backgroundColor: "#25365d" }}>
          <Text style={{ fontSize: 30, color: "#fff" }}>Text</Text>
        </View>
      </SafeAreaView>
    );
  }
}

The code above will look like:

In the root component, wrap two SafeAreaView with different colors with Fragment imported from React:

import React, { Component, Fragment } from "react";
import { SafeAreaView, Platform, View, StatusBar, Text } from "react-native";

export default class App extends Component {
  render() {
    if (Platform.OS === "ios")
      return (
        <Fragment>
          <SafeAreaView style={{ flex: 0, backgroundColor: "red" }} />
          <StatusBar barStyle="light-content" />
          <SafeAreaView style={{ flex: 1, backgroundColor: "blue" }}>
            <View style={{ flex: 1, backgroundColor: "#25365d" }}>
              <Text style={{ fontSize: 30, color: "#fff" }}>Text</Text>
            </View>
          </SafeAreaView>
        </Fragment>
      );
    else
      return (
        <View style={{ flex: 1, backgroundColor: "#25365d" }}>
          <Text style={{ fontSize: 30, color: "#fff" }}>Text</Text>
        </View>
      );
  }
}

StatusBar component sets text color of top-side status bar containing time, battery and network connection status. Let’s change StatusBar text color to white:

barStyle="light-content"

Let’s see the implementation.

Conclusion

You can use Fragment from React to wrap your SafeAreaView component without affecting UI or JavaScript logic yet can change top or bottom color of SafeAreaView’s padding.

Reference

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