모바일/React Native

[React Native] flex 속성 가로 정렬 (feat. tailwind css)

pigggulggul 2024. 12. 9. 18:15

React Native를 사용하면서 React와 같이 Tailwind CSS를 사용하여 Flex를 통한 가로 정렬을 진행할려고 했습니다.

 

React Native 코어 컴포넌트를 공부 할 때 View는 HTML의 div 태그, Text는 span 태그로 알고있기에 예상으론 가로 정렬이 되어야합니다. 그렇게 평소와 같이 가로 정렬을 위한 flex 코드를 작성했지만 가로 정렬이 먹히지 않았습니다.

export default function LoginScreen() {
  const { width, height } = Dimensions.get("window");
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParam>>();
  return (
    <View className="bg-white w-full h-full">
      <View className="flex">
        <Text className="">가로</Text>
        <Text className="">정렬</Text>
      </View>
      <Button
        title="동의하고 시작하기"
        onPress={() => navigation.navigate("MainHome")}
      />
    </View>
  );
}

 

실행결과

flex가 동작하지 않은건가?? tailwind가 역할을 못하나? 싶어 바로 개발자 도구를 켜서 확인한 결과...

 

flex 속성을 적용한 View 컴포넌트
View 컴포넌트의 flex-direction 속성

View 컴포넌트의 flex-direction는 기본적으로 column 속성이 적용되어 있는걸 확인 할 수 있었습니다. React와는 다르게 row가 기본설정이 아니기에 flex-row를 따로 설정해줘야 한다는 것을 알 수 있었습니다. 아래는 제대로 가로 정렬이 적용된 코드입니다.

export default function LoginScreen() {
  const { width, height } = Dimensions.get("window");
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParam>>();
  return (
    <View className="bg-white w-full h-full">
      <View className="flex flex-row">
        <Text className="">가로</Text>
        <Text className="">정렬</Text>
      </View>
      <Button
        title="동의하고 시작하기"
        onPress={() => navigation.navigate("MainHome")}
      />
    </View>
  );
}

 

StyleSheet를 사용하시는 분들을 위해 코드를 따로 작성하였습니다.

export default function LoginScreen() {
  const { width, height } = Dimensions.get("window");
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParam>>();
  return (
    <View style={[styles.container, { width, height }]}>
      <View style={styles.row}>
        <Text>가로</Text>
        <Text>정렬</Text>
      </View>
      <Button
        title="동의하고 시작하기"
        onPress={() => navigation.navigate("MainHome")}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: "white",
  },
  row: {
    flexDirection: "row",
  },
});