mirror of
https://github.com/Sonny93/my-links.git
synced 2025-12-10 07:25:35 +00:00
refactor: create hook screen type (instead of using plain media queries)
This commit is contained in:
24
inertia/hooks/viewport/use_media_query.tsx
Normal file
24
inertia/hooks/viewport/use_media_query.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState<boolean>(false);
|
||||
|
||||
const handleMediaChange = () => setMatches(getMediaMatches(query));
|
||||
|
||||
useEffect(() => {
|
||||
const matchMedia = window.matchMedia(query);
|
||||
handleMediaChange();
|
||||
|
||||
matchMedia.addEventListener('change', handleMediaChange);
|
||||
return () => matchMedia.removeEventListener('change', handleMediaChange);
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
function getMediaMatches(query: string): boolean {
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.matchMedia(query).matches;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
9
inertia/hooks/viewport/use_screen_type.tsx
Normal file
9
inertia/hooks/viewport/use_screen_type.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Theme } from '@emotion/react';
|
||||
import { useMediaQuery } from '~/hooks/viewport/use_media_query';
|
||||
import { media } from '~/styles/media_queries';
|
||||
|
||||
type ScreenTypes = keyof Theme['media'];
|
||||
const useScreenType = (screen: ScreenTypes) =>
|
||||
useMediaQuery(`(max-width: ${media[screen]})`);
|
||||
|
||||
export default useScreenType;
|
||||
Reference in New Issue
Block a user