728x90
728x90

Platform API

들어가며

  • 리액트 네이티브(React Native) Platform API에 대해 간단히 정리해 본다.

 

Platform API

개념

  • 리액트 네이티브에서 앱이 실행되고 있는 플랫폼(iOS, Android, Web 등)을 감지하고, 플랫폼별로 다른 동작이나 스타일을 구현할 수 있게 해주는 유틸리티

 

사용 방법

불러오기

import { Platform } from 'react-native';

 

① Platform.OS

  • 현재 실행 중인 플랫폼문자열로 반환해 준다.
    • @android@, @ios@, @web@, @windows@, @macos@
const platform = Platform.OS;

if (platform === 'android') {
  console.log('Running on Android');
} else if (platform === 'ios') {
  console.log('Running on iOS');
}

 

② Platform.select()

  • 각 플랫폼에 대해 반환할 값을 명시적으로 선언할 수 있다.
  • 내부적으로 해당 플랫폼에 맞는 값을 선택해서 반환한다.
const styles = {
  marginTop: Platform.select({
    ios: 50,
    android: 30,
    default: 10, // 나머지 플랫폼들(web 등)을 위한 fallback
  }),
};

 

⇒ @default@는 iOS/Android가 아닌 경우 사용된다.

 

③ 플랫폼별 파일 생성하기 (파일명 확장자)

  • 리엑트 네이티브에서는 파일명에 @.ios.js@, @.android.js@ 등을 붙이면, 해당 플랫폼에서만 그 파일을 자동으로 불러온다.
  • 예시
    • @Title.js@ → 기본 컴포넌트
    • @Title.ios.js@ → iOS 전용
    • @Title.android.js@ → Android 전용
  • 다른 컴포넌트에서 해당 파일을 불러와서 사용할 때, @import@는 동일하게 해준다.
    • 리액트 네이티브가 해당 플랫폼에 맞는 파일을 알아서 불러와준다.
import Title from './Title';   // 플랫폼에 따라 자동 분기된다.

 

플랫폼별 파일을 생성한 모습

 

주의 사항

  • @Platform.OS@는 런타임(Runtime)에 변하지 않는다. (앱 실행 중 바뀌지 않는다.)
  • 지나친 플랫폼 분기는 코드 가독성을 해칠 수 있으므로, 필요할 때만 사용하는 것이 적절하다.

 

정리

기능 설명 예시
@Platform.OS@ 현재 플랫폼 문자열 반환 'ios', 'android', 'web', 'windows', 'macos' 등
@Platform.select({ ... })@ 플랫폼에 따라 다른 값 선택 { ios: 20, android: 10. default: 30 }
@.ios.js@, @.android.js@ 파일 플랫폼 전용 코드 파일 생성 Title.ios.js, colors.android.js

 

사용 예제

import { StyleSheet, Text, Platform } from 'react-native';

export default function Title() {
  return (
    <Text style={styles.title}>Hello Platform!</Text>
  );
}

const styles = StyleSheet.create({
  title: {
    fontSize: 24,
    borderWidth: Platform.OS === 'android' ? 2 : 0,
    borderColor: 'black',
    padding: Platform.select({
      ios: 20,
      android: 10,
    }),
  },
});

 

참고 사이트

 

Platform · React Native

Example

reactnative.dev

 

728x90
728x90