2020-02-20 18:44:38 -05:00
|
|
|
import React, { useState, useEffect, useRef, useContext } from "react";
|
2021-01-28 12:58:35 +01:00
|
|
|
import variables from "./css/variables.module.scss";
|
2020-02-20 18:44:38 -05:00
|
|
|
|
|
|
|
const context = React.createContext(false);
|
|
|
|
|
2021-01-29 02:32:00 +05:30
|
|
|
const getIsMobileMatcher = () => {
|
|
|
|
return window.matchMedia
|
|
|
|
? window.matchMedia(variables.isMobileQuery)
|
|
|
|
: (({
|
|
|
|
matches: false,
|
|
|
|
addListener: () => {},
|
|
|
|
removeListener: () => {},
|
|
|
|
} as any) as MediaQueryList);
|
|
|
|
};
|
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const IsMobileProvider = ({
|
|
|
|
children,
|
|
|
|
}: {
|
|
|
|
children: React.ReactNode;
|
|
|
|
}) => {
|
2020-02-20 18:44:38 -05:00
|
|
|
const query = useRef<MediaQueryList>();
|
|
|
|
if (!query.current) {
|
2021-01-29 02:32:00 +05:30
|
|
|
query.current = getIsMobileMatcher();
|
2020-02-20 18:44:38 -05:00
|
|
|
}
|
|
|
|
const [isMobile, setMobile] = useState(query.current.matches);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const handler = () => setMobile(query.current!.matches);
|
|
|
|
query.current!.addListener(handler);
|
|
|
|
return () => query.current!.removeListener(handler);
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return <context.Provider value={isMobile}>{children}</context.Provider>;
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2020-02-20 18:44:38 -05:00
|
|
|
|
2021-01-29 02:32:00 +05:30
|
|
|
export const isMobile = () => getIsMobileMatcher().matches;
|
|
|
|
|
2020-02-20 18:44:38 -05:00
|
|
|
export default function useIsMobile() {
|
|
|
|
return useContext(context);
|
|
|
|
}
|