Created
October 13, 2020 15:28
-
-
Save cspilhere/b0fd3c172ffcd0c588b8bc8945b2933b to your computer and use it in GitHub Desktop.
This file contains hidden or 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, { | |
| createContext, | |
| useEffect, | |
| useState, | |
| useContext | |
| } from 'react'; | |
| const Context = createContext({}); | |
| export const ViewportProvider = ({ children }) => { | |
| const [width, setWidth] = useState(window.innerWidth); | |
| const [height, setHeight] = useState(window.innerHeight); | |
| const handler = () => { | |
| setWidth(window.innerWidth); | |
| setHeight(window.innerHeight); | |
| }; | |
| useEffect(() => { | |
| window.addEventListener('resize', handler); | |
| return () => window.removeEventListener('resize', handler); | |
| }, []); | |
| return ( | |
| <Context.Provider | |
| value={{ | |
| width, | |
| height | |
| }}> | |
| {children} | |
| </Context.Provider> | |
| ); | |
| }; | |
| const useViewport = () => { | |
| const { width, height } = useContext(Context); | |
| const breakpoints = { | |
| xs: 415, | |
| sm: 768, | |
| md: 1024, | |
| lg: 1280, | |
| xl: 2048 | |
| }; | |
| return { | |
| width, | |
| height, | |
| isXs: width > breakpoints.xs && width < breakpoints.sm, | |
| isSm: width > breakpoints.sm && width < breakpoints.md, | |
| isMd: width > breakpoints.md && width < breakpoints.lg, | |
| isLg: width > breakpoints.lg && width < breakpoints.xl, | |
| isXl: width > breakpoints.xl, | |
| isAboveXs: width > breakpoints.xs, | |
| isAboveSm: width > breakpoints.sm, | |
| isAboveMd: width > breakpoints.md, | |
| isAboveLg: width > breakpoints.lg, | |
| isBelowXs: width < breakpoints.xs, | |
| isBelowSm: width < breakpoints.sm, | |
| isBelowMd: width < breakpoints.md, | |
| isBelowLg: width < breakpoints.lg | |
| }; | |
| }; | |
| export default useViewport; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment