사용자가 웹 사이트에 접속했을 때 웹으로 접속했는지, 모바일로 접속했는지에 따라 다른 화면을 보여주려고 한다.
그러기 위해서는 현재 접속한 브라우저가 웹인지 모바일로 접속했는지에 대한 구분을 할 수 있어야 해서
방법을 찾아봤고 2가지 방법을 찾았다!
navigator.userAgent를 사용해 구분하는 방법
navigator.userAgent는 설치가 필요하지는 않다!
const [browser, setBrowser] = useState()
.
.
.
// 초기 렌더링 후 한 번만 실행하기 위해 useEffect 사용
useEffect(()=>{
const user = navigator.userAgent;
// 기본 환경 웹으로 설정
setBrowser("web")
// userAgent 문자열에 iPhone, Android 일 경우 모바일로 업데이트
if ( user.indexOf("iPhone") > -1 || user.indexOf("Android") > -1 ) {
setBrowser("mobile")
}
},[])
navigator.userAgent는 운영 체제 정보를 문자열로 반환해서 해당 문자열을 확인하여 웹과 모바일을 구분한다.
return (
browser === "web" ?
<>
<div>
...
</div>
</> :
<>
<div>
...
</div>
</>
변수 === "변수1" ? <></> : <></>
이런 형식으로 다른 div를 노출하도록 만들었다
두번째 방법으로 찾은거
react-device-detect를 설치하여 환경 구분
https://www.npmjs.com/package/react-device-detect
react-device-detect
Detect device type and render your component according to it. Latest version: 2.2.3, last published: 2 years ago. Start using react-device-detect in your project by running `npm i react-device-detect`. There are 1195 other projects in the npm registry usin
www.npmjs.com
1. react-device-detect를 설치한다
npm install --save react-device-detect
2. 사용할 페이지에서 react-device-detect를 import하여 사용
import React, { useState } from 'react';
import { BrowserView, MobileView } from 'react-device-detect';
function Main() {
return (
<div className='container'>
<BrowserView>
<Content
</Content>
</BrowserView>
<MobileView>
<ContentMobile
</ContentMobile>
</MobileView>
</div>
);
}
export default Main;
웹뷰와 모바일뷰의 컴포넌트를 따로 생성하여 불러오도록 만들었다
이렇게 작성하면 웹에서 접속시 Content를 모바일에서 접속시 ContentMobile을 불러와서 화면에 띄워준다!
단순히 화면 뿐만 아니라 import 해오는 패키지가 다른 경우에 이걸 사용해서 페이지를 분리했다