
평소 width 값을 계산할 때 calc를 자주 썼었다.
이번에 RN 개인 포폴을 진행하면서 calc를 적용할 일이 생겨서 적용을 해봤다. Web에서는 제대로 적용이 되었지만 Android 애뮬레이터에서는 적용이 안되는 모습이 보였다.
그래서 구글링을 해보았고, RN에서는 calc를 지원하지 않는다고 스택오버플로우에서 말하였다.
https://stackoverflow.com/questions/66420791/error-when-using-calc-with-react-native-and-styled-components
내가 사용하는 방법이 정답은 아니다.
나는 React Native의 Dimensions Api를 활용하였다.
Dimensions Api는 애플리케이션 창의 너비와 높이를 얻을 수 있는 Api로, 간단한 코드만으로 사용 가능하다.
import {Dimensions} from 'react-native';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
Dimensions로 화면의 크기를 가져올 수는 있지만 유동적인 화면에서는 사용하지 못하는 것이 단점이다.
import {useWindowDimensions} from 'react-native';
const {height, width} = useWindowDimensions();
이를 보완한 코드는 useWindowDimensions 훅으로, 화면 크기나 글꼴 크기가 변경되면 모든 값을 자동으로 업데이트한다.
위에서 설명한 Dimensions Api를 활용하여 기존 코드의 문제점을 파악 후 보완하여 코드를 변경하였다.
const Card = styled.View`
width: calc(50% - 21px);
`
export default function CardItem() {
const { width } = useWindowDimensions();
const cardWidth = width / 2 - 21;
return <Card width={cardWidth}/>
}
const Card = styled.View<{ width: number }>`
width: ${({ width }) => `${width}px`};
`