How to Improve UI with react-native-safe-area-context?

Learn via video courses
Topics Covered

Overview

Developers building mobile applications must frequently verify that their app's content is displayed accurately across various screen sizes and shapes, which can be a time-consuming and error-prone process. To simplify this task, developers can use tools like React Native's safe-area-context API. In this tutorial, we will explore how to use this API to position content around irregular shapes on a mobile application, such as status bars, home indicators, and notches. Prior knowledge of React Native and React Hooks is required to follow along with this tutorial.

What is react-native-safe-area-context ?

React Native Safe Area Context is a library for handling safe area insets in React Native applications. It provides a simple and consistent API for managing safe areas across different device types and screen sizes.

Getting Started

Install react-native-safe-area-context using the below commands.

For Yarn Users :-

For NPM Users :-

To use the library on your chosen platforms, it is necessary to establish a connection between the native parts of the library and your project. For instance, if you are developing an iOS application, you can link the native parts of the library by running the command npx pod-install in the terminal. This command will install the necessary dependencies and link the library to your project.

Supported Version

versionreact-native version
4.0.0+0.64.0+

The react-native architecture is currently being supported experimentally by this library, with the condition that it may undergo changes that could affect the compatibility of previous versions. As a result, only the most recent version of react-native will be supported. To utilize this library, developers will need to have version 4.4.0 or later and react-native version 0.70 or higher installed.

APIs

SafeAreaProvider

To ensure that the SafeArea is properly used in your application, it is recommended to include the SafeAreaProvider in the root component of your app. In some cases, such as when using the react-native-screens library, it may also be necessary to add the SafeAreaProvider to other areas such as the root of models and routes. It's important to keep in mind that providers should not be placed inside a View that is being animated with Animated or inside a ScrollView, as this can result in frequent updates that can impact the performance of the app.

Example:

Props

The component accepts all the properties of the View component in React Native. By default, it has a style of {flex: 1}.

initialMetrics

The "initialValue" prop is optional and its default value is null. It can be utilized to set the initial values for both "frame" and "insets", thereby allowing immediate rendering. For further details on utilizing this prop, please refer to the "optimization" section.

SafeAreaView

The SafeAreaView is a type of View component in React Native that automatically applies safe area insets as either padding or margin. To adjust the spacing within the safe area, developers can apply padding or margin styles to the insets. For instance, adding a style such as {{paddingTop: 10}} to a SafeAreaView that has insets of 20 will result in a total top padding of 30.

By utilizing the SafeAreaView component, developers can ensure that their application's content is displayed within the safe area of the device screen, avoiding any overlap with system UI elements or notches.

Example:

Props

The component accepts all the properties of the View component in React Native.

edges

The safe area insets can be customized by specifying an optional array of values for the top, right, bottom, and left edges. By default, the safe area insets apply to all edges. However, if you want to exclude certain edges from the safe area insets, you can specify their values in the array.

For instance, if a view doesn't touch the top of the screen, you can use the array to exclude the top edge from the safe area insets. This allows you to fine-tune the safe area insets based on your specific application requirements

mode

Optional, padding (default), or margin. To create a safe area-aware separator component, apply the safe area to either the padding or margin.

useSafeAreaInsets

The safe area insets of the closest provider can be retrieved and modified from JavaScript by using a particular method. It is important to keep in mind that these insets may not be updated instantaneously, which could result in a slight delay when the screen is rotated, for instance.

useSafeAreaFrame

Instead of using the Dimensions module, the nearest provider's frame can be used as an alternative.

Object with { x: number, y: number, width: number, height: number }

SafeAreaInsetsContext

It is possible to utilize React Context with the value of safe area insets in React Native. This can also be applied to class components, allowing for the creation of components that are optimized for different screen sizes and device orientations.

withSafeAreaInsets

The insets prop, which provides safe area insets, is made available by a higher-order component

initialWindowMetrics

The initial render of a window involves determining its insets and frame, which can be utilized in conjunction with the initialMetrics obtained through the SafeAreaProvider. Object with:

Deprecated APIs

useSafeArea: This function can be replaced with the useSafeAreaInsets function

SafeAreaConsumer: This function can be substituted with the SafeAreaInsetsContext.Consumer.

SafeAreaContext: This function can be replaced with the SafeAreaInsetsContext.

initialWindowSafeAreaInsets: Use initialWindowMetrics instead.

React Native Safe Area Context Web SSR

To perform server-side rendering on the web, it is possible to use the initialMetrics feature to inject frame and insets values that are specific to the user's device. If necessary, zero values can also be passed instead. This is particularly important for insets measurement, which is an asynchronous process, as failing to take this into account can disrupt the rendering of page content.

Optimizations and Testing

Using the SafeAreaView component can provide a smoother user experience as it is natively implemented and does not cause any delay when the device is rotated. Another way to optimize the initial rendering of the application is by importing the initialWindowMetrics from this package and setting it as the initialMetrics prop on the provider as explained in Web SSR.

However, this cannot be done if the provider remounts or if the application uses react-native-navigation.

React Native Safe Area Context to Avoid Notch Problems

The notch problem causes the app content to collide with the status bar on both Android and IOS devices. Let's say you want to develop a screen to show some text on the screen then the code would be:

File Name: App.js

iOS device

ios device

Android device

android device

As you can see in both devices the text content is colliding with the status bar which is not a good user experience. This notch problem can be solved using SafeAreaView present in react-native but this component is specifically designed for use in iOS devices running iOS 11 or later, thus it is not a permanent solution.

Thankfully, there exists a cross-platform solution that enables the safe handling of areas on devices with notches. This solution is known as react-native-safe-area-context and offers APIs that can be used to manage safe area insets through JavaScript. This solution is compatible with iOS, Android, and Web platforms.

Code Example

Let's look at the code example to fix the above-notch issue using a safe area context.

The SafeAreaProvider component needs to be added to either the Root Navigator or the specific screen where you want to handle safe area insets.

Paste the below code in App.js.

File Name: App.js

In this code example, the App component is wrapped with the SafeAreaProvider. This is done because the App contains only a single screen. By using the SafeAreaProvider, we can ensure that the content of the App component is displayed within the safe area of the device's screen, without being covered by the status bar, navigation bar, or device notch.

iOS device

ios device

Android device

android device

FAQs

Q: What are safe area insets?

A: Safe area insets are the areas of the device's screen that are not covered by any system UI elements, such as the status bar, navigation bar, or device notch. These areas are important for ensuring that the content of your application remains visible and accessible to the user.

Q: How does React Native Safe Area Context work?

A: React Native Safe Area Context works by providing a SafeAreaProvider component that wraps the root navigator or screen component where you want to handle safe area insets. This component exposes the safe area insets as context values that can be consumed by child components using the SafeAreaView component.

Q: Benefits of using React Native Safe Area Context?

A: The benefits of using React Native Safe Area Context include improved user experience, accessibility, and consistency across different device types and screen sizes.

Conclusion

The React Native Safe Area Context API is an essential tool for mobile application developers who need to ensure that their content is displayed correctly across different screen shapes and sizes. This tutorial has provided an overview of this API and how to use it to position webpage content around irregular shapes on a mobile application. The SafeAreaProvider, SafeAreaView, useSafeAreaInsets, and useSafeAreaFrame are some of the critical APIs that developers can use to achieve this.