add orientation context
This commit is contained in:
parent
7bddeca783
commit
d8e9eef8b1
36
src/context/OrientationContext.tsx
Normal file
36
src/context/OrientationContext.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import { Dimensions } from "react-native";
|
||||
|
||||
// Create the context
|
||||
const OrientationContext = createContext();
|
||||
|
||||
// Custom hook for consuming the context
|
||||
export const useOrientation = () => useContext(OrientationContext);
|
||||
|
||||
// Provider component
|
||||
export const OrientationProvider = ({ children }) => {
|
||||
const [orientation, setOrientation] = useState(getOrientation());
|
||||
|
||||
function getOrientation() {
|
||||
const { width, height } = Dimensions.get("window");
|
||||
return width < height ? "portrait" : "landscape";
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const updateOrientation = () => {
|
||||
setOrientation(getOrientation());
|
||||
};
|
||||
|
||||
const subscription = Dimensions.addEventListener(
|
||||
"change",
|
||||
updateOrientation,
|
||||
);
|
||||
return () => subscription.remove();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<OrientationContext.Provider value={orientation}>
|
||||
{children}
|
||||
</OrientationContext.Provider>
|
||||
);
|
||||
};
|
Loading…
Reference in New Issue
Block a user