From d8e9eef8b1e59aee678ed82b3220cdaab3c47b10 Mon Sep 17 00:00:00 2001 From: Dean Date: Tue, 20 Feb 2024 12:36:20 -0800 Subject: [PATCH] add orientation context --- src/context/OrientationContext.tsx | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/context/OrientationContext.tsx diff --git a/src/context/OrientationContext.tsx b/src/context/OrientationContext.tsx new file mode 100644 index 0000000..9ebf2a3 --- /dev/null +++ b/src/context/OrientationContext.tsx @@ -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 ( + + {children} + + ); +};