적용범위의 device prop을 받아와 상황에 맞게 컴포넌트를 화면에 뿌려줄 수 있게 해주는 라이브러리입니다.
$ npm install react-responsive --save
사용은 hook, component 방식 2종류가 있습니다.
With 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)' })
with components
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>
)
width말고도 여러 키 값들을 불러올 수 있다.
orientation, scan, aspectRatio, deviceAspectRatio, height, deviceHeight, width, deviceWidth, color, colorIndex, monochrome, resolution and type
공식 문서에 나와 있는 간단한 예제이다.
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
반응형 화면 구현할 때 마크업을 담당했었는데 너무 지저분하게 코드를 작성해 동료들이 읽는데 어려움을 많이 겪게된 것 같았다. 다른 조원분이 코드를 많이 수정해주셔서 많이 배우게 되었습니다. cors 문제를 해결하기 위해 처음 nodejs, express를 배우게 되었는데 그 부분에서 처음 배우는 부분이라 다소 구조를 익히는데 시간을 소비하게 되었습니다. 중간에 막히지 않으면 금방 끝나는 문제를 기본 3~4시간은 잡고 있다보니 진도가 더디게 나갔던 것 같았습니다. 요번 과제로 redux를 처음 제대로 써보았고 많은 시간을 들여 익숙해지게 되었습니다. 또한 react-query도 사용하였지만 아직 부족한 부분이 많아 추가적인 공부가 필요하다고 느끼고 있습니다.