import React from 'react'; import { generateMediaQuery, Mode as ModeType, Breakpoint as BreakpointType, } from './lib/generateMediaQuery'; import './Breakpoint.scss'; type At = { at: string }; type GreaterThan = { gt: string }; type LessThan = { lt: string }; type Props = (At | GreaterThan | LessThan) & { children: React.ReactNode }; export const Breakpoint: React.FC = ({ children, ...rest }) => { let mode: ModeType, breakpoint: BreakpointType; if ('at' in rest) { mode = 'at'; breakpoint = rest.at as BreakpointType; } if ('lt' in rest) { mode = 'lt'; breakpoint = rest.lt as BreakpointType; } if ('gt' in rest) { mode = 'gt'; breakpoint = rest.gt as BreakpointType; } const mediaQuery = generateMediaQuery({ mode, breakpoint: breakpoint as BreakpointType, }); const [matches, setMatches] = React.useState(true); const handleChange = React.useCallback( ({ matches }: MediaQueryListEvent): void => setMatches(matches), [], ); React.useEffect(() => { const mql = window.matchMedia(mediaQuery); mql.addListener(handleChange); return (): void => mql.removeListener(handleChange); }, [handleChange, mediaQuery]); if (typeof children === 'function') { return children({ matches }); } return ( matches && (
{children}
) ); };