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

 

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

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

 

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

 

바로 화면 크기가 변경되면 모든 값을 자동으로 업데이트 시켜주는 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

 

하나의 페이지 내에서 tab으로 분리되는 경우가 있다.

 

화면 구성(발그림)

 

탭을 ALL과 ME로 분리하고 싶다고 가정하자.

이 탭을 어떻게 구성할까?

 

useState로 상태를 관리해주면 된다.

 export type TabModeType = 'all' | 'me';
 
 export const 함수명 () => {
 	const [tabMode, setTabMode] = useState<TabModeType>('all'); // 초기 값 지정
    
    // 자유자재로 사용 가능
    const setTabModeAll = () => setTabMode('all');
    const setTabModeMe = () => setTabMode('me');
 }

 

이렇게 지정해준 뒤, 상태가 바뀜에 따라서 각각 컴포넌트를 지정해주면 된다!

 

ex)

const tabModeIsAll = tabMode === 'all';

return (
	<View>
    	<Text>{tabModeIsAll ? 'ALL' : 'ME'}</Text>
    </View>
)

 

하나의 조건을 만족할 때 여러개의 스타일 지정해주고 싶을 때가 있다.

 

필자는 아직 주니어라, 이런 방법이 있는 줄 몰랐다.

 


 

변경 전

    <SquareCheckBox
      type="for-success-routine"
      checked={succeeded}
      disabled={true}
      size={homeCheckBoxSize}
	  style={{
          borderWidth: pixel(2),
          borderStyle: 'dashed',
          borderColor: 조건 && theme.black_l_gray_d,
          backgroundColor: 조건 && theme.gray.l,
         }}
        />
       )}

 

 

변경 후

    <SquareCheckBox
      type="for-success-routine"
      checked={succeeded}
      disabled={true}
      size={homeCheckBoxSize}
	  style={{
	    ...(조건 && {
          borderWidth: pixel(2),
          borderStyle: 'dashed',
          borderColor: theme.black_l_gray_d,
          backgroundColor: theme.gray.l,
          }),
         }}
        />
       )}

이런식으로 

... (조건 && {style 속성})을 넣어주면 된다!

 


 

여기서 조심해야할 점은

&& 사용은 최대한 지양하는 것이 맞다. 따라서 삼항 연산자를 사용해서 undefined일 때까지 고려해주자!

 

* react-native-style-guide 참고

https://github.com/react-native-seoul/react-native-style-guide/blob/main/docs/ko/REACT.md

+ Recent posts