LoginSignup
6
9

More than 3 years have passed since last update.

【ReactNative】SafeAreaの余白を設定する方法(Android, iOS両方)

Posted at

SafeAreaとは?

スクリーンで言うとこの部分です。

スクリーンショット 2020-09-13 19.32.23.png

スクリーンショット 2020-09-13 19.33.16.png

上の画像は既にSafeAreaの余白を設定したあとのスクリーンショットなのですが、Viewだけで構成すると、ステータスバーにコンテンツが重なってしまいます。

対策

  1. SafeAreaViewを使う (iOS)
  2. StatusBar.currentHeightをpaddingTopに設定する (Android)

SafeAreaView

SafeAreaViewはiOSのノッチの部分の余白を取ってくれる、react-nativeが提供するコンポーネントです。このコンポーネントを使えば、iOSでノッチやステータスバーとコンテンツがかぶることはありませんが、Androidのステータスバーの余白は設定されないため、以下のように別途対応が必要になります。

StatusBar.currentHeight

StatusBarは、react-nativeが提供するコンポーネントで、StatusBar.currentHeightでステータスバーの高さを取ることができるので、paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0のようにして、Androidの場合にpaddingTopで余白を取るようにすれば良いです。

最終的には、以下のようなコードになりました。

App.tsx
import { StatusBar as ExpoStatusBar } from "expo-status-bar";
import React, { useState, useCallback } from "react";
import {
  StyleSheet,
  Platform,
  StatusBar,
  Text,
  View,
  Button,

 SafeAreaView,
} from "react-native";

export default function App() {
  const [count, setCount] = useState(0);
  const increment = useCallback(() => setCount(count + 1), [count]);

  return (
    <SafeAreaView style={styles.container}>
      <ExpoStatusBar style="auto" />
      <View>
        <Text>Open up App.tsx to start working on your app!</Text>
        <Text>Count = {count}</Text>
        <Button title="Count Up" onPress={increment} />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
  },
});

参考にしたStackOverflowの記事

6
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9