Skip to main content

Command Palette

Search for a command to run...

React 반응형 라이브러리로 Web/Mobile 구분하기

Published
3 min readView as Markdown
K

프론트엔드 개발자 김가영입니다. 개발과 일에 대한 생각을 주로 씁니다. https://velog.io/@kykim_dev/posts (2023 이전 블로깅)

image.jpg

  • React로 어플리케이션 구현 시, PC와 Mobile을 구분해서 반응형으로 제작할 때 npm 라이브러리를 사용할 수 있다.

  • 대표적으로 react-device-detect' , ’react-responsive' 가 있으며, 사용률은 npm trends 기준 react-device-detect 가 높다.

react-device-detect

  • 플랫폼/디바이스를 확인해 분기 처리할 수 있으며, 특정 조건에 맞춰 Android/IOS에 따라 해당 어플리케이션으로 링크 연결도 가능하다.

설치

npm install react-device-detect --save or yarn add react-device-detect

사용

  • 브라우저/모바일 뷰가 필요한 경우
 import { BrowserView, MobileView, isBrowser, isMobile } from 'react-device-detect';

<BrowserView> <h1>This is rendered only in browser</h1> </BrowserView>
<MobileView> <h1>This is rendered only on mobile</h1> </MobileView>

  • 모바일 뷰만 필요한 경우 : isMobile 조건 추가
 import {isMobile} from 'react-device-detect';

function App() {
  renderContent = () => {
    if (isMobile) {
      return <div> This content is available only on mobile</div>
    }
    return <div> ...content </div>
  }

  render() {
    return this.renderContent();
  }
}
  • 특정 브라우저/디바이스에 따른 화면 구현할 경우
import { browserName, CustomView } from 'react-device-detect';

function App() {
  render() {
    return (
      <CustomView condition={browserName === "Chrome"}>
        <div>...content</div>
      </CustomView>
    )
  }
}
  • 지원하지 않는 브라우저에 접속했을 경우
import { isIE } from 'react-device-detect';

function App() {
  render() {
    if (isIE) return <div> IE is not supported. Download Chrome/Opera/Firefox </div>
    return (
      <div>...content</div>
    )
  }
}

react-responsive

  • 반응형 디자인을 위한 React의 미디어쿼리로 useMediaQuery Hook을 사용해 브라우저 크기(width)에 따른 화면 구현이 가능하다.

  • 화면 별 특정 사이즈를 직접 지정할 수 있어 다양한 화면 크기를 안정적으로 반응형으로 바꿔줄 수 있고, 자동 인식이 어려운 브라우저를 섬세하게 컨트롤 할 수 있다는 장점이 있다.

설치

 $ npm install react-responsive --save

사용

  • Hooks 만들기
import React from "react";
import { useMediaQuery } from "react-responsive";

const Example = () => {
  const isDesktopOrLaptop = useMediaQuery({
    query: "(min-width: 1224px)",
  });
  const isBigScreen = useMediaQuery({ query: "(min-width: 1824px)" });
  const isTabletOrMobile = useMediaQuery({ query: "(max-width: 1224px)" });
  const isPortrait = useMediaQuery({ query: "(orientation: portrait)" });
  const isRetina = useMediaQuery({ query: "(min-resolution: 2dppx)" });

  return (
    <div>
      <h1>Device Test!</h1>
      {isDesktopOrLaptop && <p>You are a desktop or laptop</p>}
      {isBigScreen && <p>You have a huge screen</p>}
      {isTabletOrMobile && <p>You are a tablet or mobile phone</p>}
      <p>Your are in {isPortrait ? "portrait" : "landscape"} orientation</p>
      {isRetina && <p>You are retina</p>}
    </div>
  );
};
  • 컴포넌트에서 쓰기
import MediaQuery from "react-responsive";

const Example = () => (
  <div>
    <h1>Device Test!</h1>
    <MediaQuery minWidth={1224}>
      <p>You are a desktop or laptop</p>
      <MediaQuery minWidth={1824}>
        <p>You also have a huge screen</p>
      </MediaQuery>
    </MediaQuery>
    <MediaQuery minResolution="2dppx">
      {/* You can also use a function (render prop) as a child */}
      {(matches) =>
        matches ? <p>You are retina</p> : <p>You are not retina</p>
      }
    </MediaQuery>
  </div>
);
  • device props로 쓰기
import { useMediaQuery } from "react-responsive";

const Example = () => {
  const isDesktopOrLaptop = useMediaQuery(
    { minDeviceWidth: 1224 },
    { deviceWidth: 1600 }, // `device` prop
  );

  return (
    <div>
      {isDesktopOrLaptop && (
        <p>
          this will always get rendered even if device is shorter than 1224px,
          that's because we overrode device settings with 'deviceWidth: 1600'.
        </p>
      )}
    </div>
  );
};
  • breakpoints 설정해서 간단하게 쓰기
import { useMediaQuery } from "react-responsive";

const Desktop = ({ children }) => {
  const isDesktop = useMediaQuery({ minWidth: 992 });
  return isDesktop ? children : null;
};
const Tablet = ({ children }) => {
  const isTablet = useMediaQuery({ minWidth: 768, maxWidth: 991 });
  return isTablet ? children : null;
};
const Mobile = ({ children }) => {
  const isMobile = useMediaQuery({ maxWidth: 767 });
  return isMobile ? children : null;
};
const Default = ({ children }) => {
  const isNotMobile = useMediaQuery({ minWidth: 768 });
  return isNotMobile ? children : null;
};

const Example = () => (
  <div>
    <Desktop>Desktop or laptop</Desktop>
    <Tablet>Tablet</Tablet>
    <Mobile>Mobile</Mobile>
    <Default>Not mobile (desktop or laptop or tablet)</Default>
  </div>
);

export default Example;

정리

  • 특정 브라우저 타입(Chrome, Safari, IE) 혹은 특정 카테고리 디바이스(all iPods..) 인식이 필요한 경우 react-device-detect 를,

  • 전반적인 모바일 환경 대응이 필요한 경우에는 CSS ‘@media queries(react-responsive)’나 ‘matchMedia’ 를 쓸 수 있다.

More from this blog

React 렌더링 최적화

React 렌더링이란? 리액트에서 렌더링이란, 컴포넌트가 현재 props와 state의 상태에 기초하여 UI를 어떻게 구성할지 컴포넌트에게 요청하는 작업을 의미한다. 즉 사용자 화면에 View(내용)를 보여 주는 것. 초기 렌더링 렌더링을 담당하는 render 함수는 컴포넌트의 정보를 이용해 화면을 구성(렌더링)한다. 컴포넌트 내부에는 또 다른 컴포넌트들이 들어갈 수 있어, render 함수가 실행되면 그 내부에 있는 컴포넌트들도 재귀적으로 렌...

May 21, 20243 min read

로컬에서 Aws Ec2 인스턴스에 배포하기

EC2 (컴퓨팅) Elastic Compute Cloud(EC2)로 클라우드 컴퓨팅 서비스 클라우드를 통해 서버, 스토리지, 데이터베이스 등의 컴퓨팅 서비스를 제공하는 것으로 AWS에서 원격으로 제어할 수 있는 가상의 컴퓨터 한 대를 임대하는 것과 같다. 제공되는 가상 이미지를 ‘인스턴스(Instance)’라고 하며, 필요에 따라 사양(CPU 코어 수, 메모리 용량, 스토리지)을 변경할 수 있다. 서버에 Build 가져오기 1. 로컬에...

Apr 10, 20242 min read

DevNotes by kykim

23 posts