모바일 기기는 화면 크기가 천차만별이다.

 

문제의 화근은 갤럭시 폴드였다.

처음 빌드할 때 화면의 크기에 따라 미리 지정해 줄 수는 있지만, 동작에 따라 화면의 크기가 달라지는 폴드 같은 경우에는 예외였다.

 

이런 상황에서 어떻게 할 수 있을까?

 

바로 화면 크기가 변경되면 모든 값을 자동으로 업데이트 시켜주는 useWindowDimesions을 사용하면 된다.

useWindowDimesions은 react-native에서 기본적으로 제공해주는 API 이다.

 


 

다른 곳에서도 사용할 수 있도록 hook으로 만들어보자.

기기의 width가 650px이 넘으면 넓은 것으로 판단했다.

interface UseWindowDimensionsOutput extends ScaledSize {
  isWide: boolean;
}

export const getWidthIsWide = (width: number) => {
  return width >= 650 ? true : false;
};

export const useMyDimensions = (): UseWindowDimensionsOutput => {
  const useWindowDimensionsOutput = useWindowDimensions();
  const { width } = useWindowDimensionsOutput;
  const isWide = getWidthIsWide(width);

  return {
    ...useWindowDimensionsOutput,
    isWide,
  };
};

ScaledSize를 상속받고, ...useWindowDimensionsOutput을 자체로 리턴해주면
쓰이는 곳에서 부모의 프로퍼티를 그대로 사용할 수 있다. 

따라서 width, height, scale, fontScale을 자유자재로 사용할 수 있다.

 

 

 

<참고 자료>

https://reactnative.dev/docs/usewindowdimensions

 

useWindowDimensions · React Native

useWindowDimensions automatically updates all of its values when screen size or font scale changes. You can get your application window's width and height like so:

reactnative.dev

 

+ Recent posts