React 입문(5) : react-device-detect : Library for Cross-Platform Application Development (last update: 2020.12.21.)

devpark·2020년 12월 21일
0

React.js & JavaScript

목록 보기
5/11

2. react-device-detect : for Crossing-Platform

Notion의 React.js Libraries & API 통합 페이지 바로가기


0. References

react-device-detect -npmjs.com
Is it possible to use if...else... statement in React render function? -stackoverflow


1. Introduction

Cross-Platform, 즉 범 플랫폼 웹/앱으로 구성하기 위해 필요한 플랫폼/디바이스의 추적(device detection) 및 분기 처리 구문을 작성하기 위해 사용할 수 있는 라이브러리이다. 이는 Browser/Mobile을 손 쉽게 구분하여 <BrowserView><MobileView> 태그의 내부에 작성한 elements를 화면에 분리 노출하는 것이 가능하며, 특정 device 또는 조건으로 한정하여 view를 렌더링하고 스타일링을 대입하는 등의 처리가 가능하다.


2. Installation & Type Command

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

cd ..로 설치 경로를 특정한 후 npm 또는 yarn을 선택하여 위의 comman를 입력하면 설치된다.


3. Syntax & Documentations

Importing

import {
  BrowserView,
  MobileView,
  isBrowser,
  isMobile
} from "react-device-detect";

우선 라이브러리를 사용하기 위해 위와 같은 코드로 Importing 해 준다. 여기서 BrowserView와 MobileView는 Browser/Mobile을 나누어 view단에 노출할 코드를 작성하기 위함이며, isBrowser와 isMobile은 Browser와 Mobile을 식별하여 분기 처리를 하기 위해서다.

Browser-view / Mobile-view

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

위의 코드와 같이 Browser에 노출할 view와 Mobile에 노출할 view를 나눠서 코드를 작성할 수 있다. BrowserView 태그 내부에 작성한 내용은 실제로 Mobile에서 접속하였을 때 화면단에 노출되지 않으며, 그 반대의 경우도 마찬가지이다.

leave a messages to a specific browser/os

import { isIE } from 'react-device-detect';
render(){
	if(isIE) return <div> IE is not supported. Download Chrome/Opera/Firefox </div>
return(
	<div> else : CONTENTS ON HERE</div>
	);
}

also can render a view on a specific device and with a specific condition

import{ browserName, customView } from 'react-device-detect';
render(){
	return(
		<CustomView condition={ browserName === "Chrome" }>
			<div>CONTENTS ON HERE</div>
		</CustomView>
	);
}

Styling
view Component를 스타일링 할 때는 class를 viewClassName prop으로 넘겨준다.
*you can style view component by passing class to viewClassName prop.*

<BrowserView viewClassName="custom-class">
	<p> VIEW CONTENT ON HERE </p>
</BrowserView>

또는 inline-스타일들을 style prop으로 넘길 수 있다.
or you can pass inline styles to style prop.

const styles = {
	background: 'red';
	fontSize: '24px';
lineHeight: '2';
};
<BrowserView style={ styles }>
	<p> View content </p>
</BrowserView>

4. Examples & Usages

  • Requirement Analysis : Device Detect also Crossing Platform

    1. 하나의 웹 페이지를 통해 Platform Crossing이 가능하여야 한다. 즉, 디바이스 무관 browser 상에 동일하게 노출할 페이지를 제작하되 반드시 반응 형 페이지로 구성한다.
    2. 단, 디바이스별 페이지 이동 분기가 존재한다. pc에서 브라우저를 통해 주문 기능에 접근하는 경우 별도의 modal을 추가로 띄워 별도의 안내 메세지를 출력하도록 한다.
    3. 모바일에서 브라우저를 통해 접근하는 경우, 해당 디바이스의 os에 따라 분기한다. 안드로이드/ios 기기의 각 os에 맞게 어플리케이션 설치 화면으로 넘어가거나, 실제 어플리케이션의 상세 페이지로 이동할 수 있게 한다.
  • Conclusion

    따라서 디바이스별/os별 분기 처리는 다음과 같이 진행한다:

    1. Mobile (mobile + tablet) / PC
      1. PC : Modal(Rodal) 제어
      2. Mobile - Android / IOS
        1. Android
          1. App 미설치 : Google Playstore 설치 화면으로 이동
          2. App 설치 : Deeplink*를 통해 앱 내 실제 상품 페이지로 이동
        2. IOS
          1. App 미설치 : Appstore 설치 화면으로 이동
          2. App 설치 : Deeplink*를 통해 앱 내 실제 상품 페이지로 이동

e.g.

...
import { isMobile, isAndroid, isIOS, CustomView } from 'react-device-detect';
class App extends Component{
  constructor(props){
    super(props);
    this.state = {
      visible: false,
    };
  }
  show(){
    this.setState({ visible: true });
  }
  hide(){
    this.setState({ visible: false });
  }
// 앱 미설치시 지정 경로로 이동할 수 있는 함수를 os별 각각 선언
  android(){
    window.location.href="https://playstore-link.com";
  }
  ios(){
    window.location.href="https://appstore-link.com";
  }
	render(){
    return(
		<React.Fragment>
...
{/* CONDITIONAL RENDERING FROM HERE */}
          {(() => {
// CONDITION 1: MOBILE-IOS
// 범모바일이며 동시에 IOS인 경우 = 접속 디바이스가 아이폰/아이패드인 경우
        if (isMobile && isIOS) {
          return (
              <div className="order-btn-wrapper" onClick={ this.ios } >
                  <div className="order-btn" id="order-btn">ORDER :: IOS/div>
              </div>
          )
// CONDITION 2 : MOBILE-ANDROID
// 범모바일이며 동시에 ANDROID인 경우 = 접속 디바이스가 안드로이드 핸드폰/태블릿인 경우
        } else if (isMobile && isAndroid) {
          return (
              <div className="order-btn-wrapper" onClick={ this.android } >
                  <div className="order-btn" id="order-btn">ORDER :: ANDROID</div>
            </div>
          )
// CONDITION 3: WEB-PC
// 그 외의 경우 : 즉 PC 접속인 경우
        } else {
          return (
// 복수의 구성요소들을 내포하고 있으므로 반드시 묶어준다.
          <React.Fragment>
            <div className="order-btn-wrapper" onClick={ this.show.bind(this) } >
            <div className="order-btn" id="order-btn">ORDER :: PC</div>
            </div>
// 범모바일 외 디바이스 전용-별도 정의 VIEW를 선언한다 :
            <CustomView condition={ !isMobile }>
// 여기서부터 RODAL 선언 및 제어
              <Rodal visible={ this.state.visible } onClose={ this.hide.bind(this) } 
                     className="rodal-slideDown-enter rodal-outermost" animation="slideDown" width="280" height="164"
                     showCloseButton="false" >
                <div className="rodal-container">
                <div className="rodal-wrapper">
                  <span className="rodal-msg">
                    LOREM
                    <br/>
                    IPSUM NEQUE EST
                    <br/>
                  </span>
                </div>
                    <a href="https://appstore-link.com" className="rodal-link">SEE ALSO</a>
                    <div className="rodal-hr">
                      </div>
                      <span className="rodal-confirm" onClick={ this.hide.bind(this) }>
                        OKAY
                        </span>
                    </div>
              </ Rodal>
            </CustomView>
          </React.Fragment>
          )
        }
      })()}
      {/* END OF CONDITIONAL RENDERING */}
...

profile
아! 응응애에요!

0개의 댓글