safe-area/Guides

Safe Area Optimizations

Web SSR, performance optimizations, and testing best practices

optimizationssrtestingperformance

Safe Area Optimizations

Web SSR

If you are doing server side rendering on the web you can use initialMetrics to inject insets and frame value based on the device the user has, or simply pass zero values. Since insets measurement is async it will break rendering your page content otherwise.

SafeAreaView

If you can, use SafeAreaView. It's implemented natively so when rotating the device, there is no delay from the asynchronous bridge.

initialWindowMetrics

To speed up the initial render, you can import initialWindowMetrics from this package and set as the initialMetrics prop on the provider as described in Web SSR. You cannot do this if your provider remounts, or you are using react-native-navigation.

import {
  SafeAreaProvider,
  initialWindowMetrics,
} from 'react-native-safe-area-context';

function App() {
  return (
    <SafeAreaProvider initialMetrics={initialWindowMetrics}>
      ...
    </SafeAreaProvider>
  );
}

Testing

Built in mocks

This library includes a built in mock for Jest. It will use the following metrics by default:

{
  frame: {
    width: 320,
    height: 640,
    x: 0,
    y: 0,
  },
  insets: {
    left: 0,
    right: 0,
    bottom: 0,
    top: 0,
  },
}

To use it, add the following code to the jest setup file:

import mockSafeAreaContext from 'react-native-safe-area-context/jest/mock';

jest.mock('react-native-safe-area-context', () => mockSafeAreaContext);

To have more control over the test values it is also possible to pass initialMetrics to SafeAreaProvider to provide mock data for frame and insets.

export function TestSafeAreaProvider({ children }) {
  return (
    <SafeAreaProvider
      initialMetrics={{
        frame: { x: 0, y: 0, width: 0, height: 0 },
        insets: { top: 0, left: 0, right: 0, bottom: 0 },
      }}
    >
      {children}
    </SafeAreaProvider>
  );
}

Enabling Babel Parsing for Modules

While trying to use this mock, a frequently encountered error is:

SyntaxError: Cannot use import statement outside a module.

This issue arises due to the use of the import statement. To resolve it, you need to permit Babel to parse the file.

By default, Jest does not parse files located within the node_modules folder.

However, you can modify this behavior as outlined in the Jest documentation on transformIgnorePatterns customization. If you're using a preset, like the one from react-native, you should update your Jest configuration to include react-native-safe-area-context as shown below:

transformIgnorePatterns: [
  'node_modules/(?!((jest-)?react-native|@react-native(-community)?|react-native-safe-area-context)/)',
];

This adjustment ensures Babel correctly parses modules, avoiding the aforementioned syntax error.