Last active
November 12, 2021 02:07
-
-
Save gjuoun/64756f9edefcb346eefaa16834ab9ca8 to your computer and use it in GitHub Desktop.
breakPoint-with-recoil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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</> | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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