Created
January 4, 2021 08:01
-
-
Save nabettu/a22f0166261957e9f3959c4966c30ff3 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, { useState, createContext, useContext, useEffect } from "react"; | |
import { Dimensions } from "react-native"; | |
type ScreenSizeContextType = { | |
windowWidth: number; | |
windowHeight: number; | |
}; | |
export const ScreenSizeContext = createContext<ScreenSizeContextType>({ | |
windowWidth: Dimensions.get("window").width, | |
windowHeight: Dimensions.get("window").height | |
}); | |
export const ScreenSizeProvider = ({ children }) => { | |
const [windowWidth, setWindowWidth] = useState<number>( | |
Dimensions.get("window").width | |
); | |
const [windowHeight, setWindowHeight] = useState<number>( | |
Dimensions.get("window").height | |
); | |
const handleChangeWindowSize = (e) => { | |
const { width, height } = e.window | |
setWindowWidth(width); | |
setWindowHeight(height); | |
}; | |
useEffect(() => { | |
Dimensions.addEventListener("change", handleChangeWindowSize); | |
return Dimensions.removeEventListener("change", handleChangeWindowSize); | |
}, []); | |
return ( | |
<ScreenSizeContext.Provider value={{ windowWidth, windowHeight }} > | |
{children} | |
</ScreenSizeContext.Provider> | |
); | |
}; | |
export const useScreenSize = () => useContext(ScreenSizeContext); | |
export default ScreenSizeProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment