2020-02-20 18:44:38 -05:00
|
|
|
import React, { useState, useEffect, useRef, useContext } from "react";
|
|
|
|
|
|
|
|
const context = React.createContext(false);
|
|
|
|
|
|
|
|
export function IsMobileProvider({ children }: { children: React.ReactNode }) {
|
|
|
|
const query = useRef<MediaQueryList>();
|
|
|
|
if (!query.current) {
|
2020-02-21 08:17:20 -05:00
|
|
|
query.current = window.matchMedia
|
|
|
|
? window.matchMedia(
|
|
|
|
"(max-width: 600px), (max-height: 500px) and (max-width: 1000px)",
|
|
|
|
)
|
|
|
|
: (({
|
|
|
|
matches: false,
|
|
|
|
addListener: () => {},
|
|
|
|
removeListener: () => {},
|
2020-04-14 12:30:58 +03:00
|
|
|
} as any) as MediaQueryList);
|
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>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function useIsMobile() {
|
|
|
|
return useContext(context);
|
|
|
|
}
|