React에서 모바일 기기 접근을 감지할 수 있는 방법을 찾던 중 react-device-detect라는 라이브러리를 발견했는데 react-device-detect는 아주 간단하게 모바일 접근을 감지할 수 있었습니다.
https://www.npmjs.com/package/react-device-detect
yarn add react-device-detect
import React from 'react';
import styled from 'styled-components';
import mobilePreparingImg from 'assets/img/img_mobile_preparing.png';
const MobilePage = () => {
const handleLinkCopy = () => {
navigator.clipboard.writeText(document.location.href);
alert('링크가 복사되었습니다!');
};
return (
<MobilePageWrapper>
<img src={mobilePreparingImg} alt="mobile icon" />
<p className="title">PC버전으로 접속해주세요</p>
<p className="description">
아쉽게도 모바일은 지원하지 않아요😥 <br />
PC환경에서 테이커스를 이용해주세요!
</p>
<button className="link-copy-button" onClick={handleLinkCopy}>
링크 복사하기
</button>
</MobilePageWrapper>
);
};
/** styled components */
export default MobilePage;
isMobile 사용하기
import React from 'react';
import { isMobile } from 'react-device-detect';
import GlobalStyle from './styles/GlobalStyle';
import styled from 'styled-components';
import { Header, Footer } from './components/index';
import LoginProvider from './lib/context/provider';
import { MobilePage } from 'pages';
function App() {
return (
<>
<GlobalStyle />
{isMobile ? (
<MobilePage />
) : (
<Router>
<LoginProvider>
<Header />
/** content */
<Footer />
</LoginProvider>
</Router>
)}
</>
);
}
export default App;
첫번째 방법은 isMobile과 삼항 연산자를 사용하여 조건부 렌더링을 하는 방법입니다. 이 방법도 간편하긴 하지만 App.jsx의 내용이 복잡해지면 코드를 알아보기 힘들어질 수도 있습니다.
MobileVuew
BrowserView
사용
import React from 'react';
import { BrowserView, MobileView } from 'react-device-detect';
import GlobalStyle from './styles/GlobalStyle';
import styled from 'styled-components';
import { Header, Footer } from './components/index';
import LoginProvider from './lib/context/provider';
import { MobilePage } from 'pages';
function App() {
return (
<>
<GlobalStyle />
<MobileView>
<MobilePage />
</MobileView>
<BrowserView>
<Router>
<LoginProvider>
<Header />
/** content */
<Footer />
</LoginProvider>
</Router>
</BrowserView>
</>
);
}
export default App;
두번째 방법은 BrowserView
와 MobileView
를 사용하는 방식입니다!
react-device-detect에는 isMobile``MobileView``BrowserView
외에도 isIE
와 같은 다른 기능들도 있으니 확인해보시면 좋을 것 같습니다!