add orientation context

This commit is contained in:
Dean 2024-02-20 12:36:20 -08:00
parent 7bddeca783
commit d8e9eef8b1

View 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>
);
};