media query와 react custom-hook 을 활용해서 반응형 작업하기.

hyeok·2022년 4월 24일
0

StyledComponent 에서도 mediaquery는 잘 사용가능하다.

const StyledCard = styled(Card)(({ theme }) => {
  return {
    [`@media (max-width: ${theme.mobileMedia})`]: {
      [".ant-card-head-wrapper"]: {
        flexDirection: "column",
      },
      ".ant-steps-vertical": {
        flexDirection: "row",
      },
      ".ant-card-extra": {
        marginLeft: 0,
      },
    },
  };
});

max-width는 themeProvider에서 가져온 theme로 정의했다. 추후에 나중에 mobile의 기준인 max-width가 바뀌거나 한다면 쉽게 전체적으로 바꿀수 있다.

그런데 랜더링 되는 돔에서 mobile인지 아닌지를 확인해야할 경우가 있다. 인라인으로 적용되는 스타일 api에서 변경을 하거나 돔 자체가 다른 돔이 나올경우다.

이럴 경우엔 커스텀 훅을 하나 만들어서 쉽게 모바일 최적화 가능하다.


function useResponseLayout() {
  const theme = useContext(ThemeContext);

  const [isMobile, setIsMobile] = useState<boolean>(false);

  useEffect(() => {
    const init = () => {
      const mobileSize = theme?.mobileMedia.replace("px", " ");
      if (Number.parseInt(mobileSize) > window.innerWidth) {
        setIsMobile(true);
      } else {
        setIsMobile(false);
      }
    };
    init();
    window.addEventListener("resize", init);
    return () => window.removeEventListener("resize", init);
  }, []);

  return { isMobile };
}

이 커스텀 훅은 화면의 "resize"이벤트를 감지하고 화면 크기에 따라서 isMobile의 스테잇 값을 결정한다.
이거 또한 theme에서 가져온 값을 모바일을 구분하는maxwidth값을 정했다.

이걸 커스텀 훅을 활용하면

const isMobile = useResponse()
로 불러와서 모바일 최적화에 사용가능하다. 기준이 되는 width에 따라서 true, false boolean값을 구분해서 내뱉는다.

mediaquery와 이 커스텀 훅을 활용해서 현재 외주 서비스 모바일 최적화 진행중에 있다.

profile
내가 만든 소프트웨어가 사람들을 즐겁게 할 수 있기 바라는 개발자

0개의 댓글