Created
December 16, 2021 17:39
-
-
Save gnbaron/5d1e0f4c304c25b29f362e8a0fa1a8cd to your computer and use it in GitHub Desktop.
Responsive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, ReactNode } from "react" | |
export function useMediaQuery(query: string) { | |
const [matches, setMatches] = useState(false) | |
useEffect(() => { | |
const media = window.matchMedia(query) | |
if (media.matches !== matches) { | |
setMatches(media.matches) | |
} | |
const listener = () => { | |
setMatches(media.matches) | |
} | |
media.addEventListener("change", listener) | |
return () => media.removeEventListener("change", listener) | |
}, [matches, query]) | |
return matches | |
} | |
export function useIsWideScreen() { | |
return useMediaQuery("(min-width: 768px)") | |
} | |
type Props = { | |
children: ReactNode | |
} | |
export const OnlySmallScreen = ({ children }: Props) => (useIsWideScreen() ? null : <>{children}</>) | |
export const OnlyWideScreen = ({ children }: Props) => (useIsWideScreen() ? <>{children}</> : null) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment