Skip to content

Instantly share code, notes, and snippets.

@gjuoun
Last active November 12, 2021 02:07
Show Gist options
  • Save gjuoun/64756f9edefcb346eefaa16834ab9ca8 to your computer and use it in GitHub Desktop.
Save gjuoun/64756f9edefcb346eefaa16834ab9ca8 to your computer and use it in GitHub Desktop.
breakPoint-with-recoil
import { nanoid } from "nanoid";
import { atom } from "recoil";
import UAParser from 'ua-parser-js'
interface BreakPoint{
isMobile: boolean
isLaptop: boolean
isTablet: boolean
}
const getBreakPoints = () => {
const parser = new UAParser()
const deviceType = parser.getDevice().type
const breakPoint: BreakPoint = {
isLaptop: false,
isMobile: false,
isTablet: false,
}
if(deviceType === 'mobile'){
breakPoint.isMobile = true
}else if(deviceType === 'tablet'){
breakPoint.isTablet = true
}else{
breakPoint.isLaptop = true
}
return breakPoint
}
export const breakPointState = atom<BreakPoint>({
key: "breakPointState"+ nanoid(),
default: getBreakPoints()
})
import React, { useEffect } from 'react'
import { useRecoilValue, useSetRecoilState } from 'recoil'
import { breakPointState } from './Home.recoil'
export const BreakPoint = () => {
const { isLaptop, isMobile, isTablet } = useRecoilValue(breakPointState)
const setBreakPoint = useSetRecoilState(breakPointState)
useEffect(() => {
const watchBreakPoint = () => {
const windowWidth = window.innerWidth
setBreakPoint({
isLaptop: windowWidth >= 1024,
isTablet: windowWidth>= 640 && windowWidth < 1024,
isMobile: windowWidth < 640
})
}
window.addEventListener('resize', watchBreakPoint)
window.addEventListener('focus', watchBreakPoint)
watchBreakPoint()
return () => {
window.removeEventListener('resize', watchBreakPoint)
}
}, [setBreakPoint])
if (isLaptop) {
return <>isLaptop</>
} else if (isTablet) {
return <>isTablet</>
} else {
return <>mobile</>
}
}
dependencies:
react
nanoid
recoil
ua-parser-js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment