Skip to content

Instantly share code, notes, and snippets.

@gnbaron
Created December 16, 2021 17:39
Show Gist options
  • Save gnbaron/5d1e0f4c304c25b29f362e8a0fa1a8cd to your computer and use it in GitHub Desktop.
Save gnbaron/5d1e0f4c304c25b29f362e8a0fa1a8cd to your computer and use it in GitHub Desktop.
Responsive
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