Language/React

[react-responsive, react-device-detect] 리액트 반응형 모듈 사용하기

jaewpark 2021. 12. 28. 16:21

프로젝트를 하다보니 사용자의 편의성에 맞추기 위해서는 반응형 웹을 사용하는 것은 필연적이라 생각이 들었는데요. 그래서 모듈을 찾다보니 여러가지가 나오지만 그 중에서도 react-responsivereact-device-detect를 비교를 하면 화면의 크기와 기기 종류로 판단하여 사용한다.

 

react-responsive

아래와 같이 useMediaQuery를 사용하여 크기에 따라서 어떻게 반응할지 혹은 가로/세로모드에 따라서 어떻게 반응해야 되는지 Hooks을 통해서 변화를 줄 수 있다.

import React from 'react';
import {useMediaQuery} from 'react-responsive';

export default function TestMap() {
  const isDesktop = useMediaQuery({query: '(min-width: 1440px)'});
  const isMobile = useMediaQuery({query: '(max-width: 1439px)'});
  const isPortrait = useMediaQuery({query: '(orientation: portrait)'});
  return (
    <>
      <h1>Test!</h1>
      {isDesktop && <p>You are Desktop</p>}
      {isMobile && <p>You are mobile</p>}
      <p>Your are in {isPortrait ? 'portrait' : 'landscape'} orientation</p>
    </>
  );
}

 

react-device-detect

플랫폼/디바이스를 확인하여 분기 처리 구문을 작성할 수 있게 되었다. 자세한 것은 아래와 같이 코드를 확인하면 된다.

import React from 'react';
import {BrowserView, MobileView} from 'react-device-detect';

export default function TestMap() {
  return (
    <>
      <h1>Test!</h1>
      <BrowserView>
        <p>You are Desktop</p>
      </BrowserView>
      <MobileView>
        <p>You are mobile</p>
      </MobileView>
    </>
  );
}
import{browserName, customView} from 'react-device-detect';
render(){
	return(
		<CustomView condition={ browserName === "Chrome" }>
			<div>CONTENTS ON HERE</div>
		</CustomView>
	);
}

특정 조건에 맞춰서 android 혹은 ios 접속에 따라서 해당 어플로 링크로 연결할 수도 있는 방법이 있다.

import { isMobile, isAndroid, isIOS, CustomView } from 'react-device-detect';
class App extends Component{
  constructor(props){
    super(props);
  }
  android(){
    window.location.href="android app link";
  }
  ios(){
    window.location.href="ios app link";
  }
	render(){
    return(
		<React.Fragment>
		...
          {(() => {
        if (isMobile && isIOS) {
          return (
            <div className="order-btn-wrapper" onClick={ this.ios } >
               <div className="order-btn" id="order-btn">IOS/div>
            </div>
          )
        } else if (isMobile && isAndroid) {
          return (
            <div className="order-btn-wrapper" onClick={ this.android } >
                <div className="order-btn" id="order-btn">ANDROID</div>
            </div>
          )
        } else {
          return (
          	<div> PC </div>
            )
          </React.Fragment>
          )
        }
      })()}

 


 

결과로는 하고자 하는 프로젝트에 맞춰서 사용을 하면 되는데, 지금 프로젝트에서 사용하고자 찾아본 모듈이지만 추후에는 어플로도 만들어져야 범용적으로 쓸 수 있기 때문에, react-device-detect을 사용하려고 한다.