|
| 1 | +import React, {useRef, useEffect} from 'react'; |
| 2 | + |
| 3 | +// Default breakpoints that should apply to all observed |
| 4 | +// elements that don't define their own custom breakpoints. |
| 5 | +const defaultBreakpoints = { |
| 6 | + SM: 384, |
| 7 | + MD: 576, |
| 8 | + LG: 768, |
| 9 | + XL: 960, |
| 10 | +}; |
| 11 | + |
| 12 | +export default function Div({ breakpoints: customBreakpoints, ...props }) { |
| 13 | + const breakpoints = customBreakpoints || defaultBreakpoints; |
| 14 | + const containerRef = useRef(null); |
| 15 | + useResizeObserver(breakpoints, containerRef); |
| 16 | + return ( |
| 17 | + <div ref={containerRef} {...props} /> |
| 18 | + ); |
| 19 | +} |
| 20 | + |
| 21 | +export function useResizeObserver(breakpoints, containerRef) { |
| 22 | + useEffect(() => { |
| 23 | + if (window.ResizeObserver) { |
| 24 | + const ro = new window.ResizeObserver((entries) => { |
| 25 | + entries.forEach((entry) => { |
| 26 | + // Update the matching breakpoints on the observed element. |
| 27 | + Object.keys(breakpoints).forEach(breakpoint => { |
| 28 | + const minWidth = breakpoints[breakpoint]; |
| 29 | + if (entry.contentRect.width >= minWidth) { |
| 30 | + entry.target.classList.add(breakpoint); |
| 31 | + } else { |
| 32 | + entry.target.classList.remove(breakpoint); |
| 33 | + } |
| 34 | + }); |
| 35 | + }); |
| 36 | + }); |
| 37 | + ro.observe(containerRef.current); |
| 38 | + return () => ro.disconnect(); |
| 39 | + } else if (process && process.env.NODE_ENV === 'development') { |
| 40 | + console.warn('Resize observer not supported'); |
| 41 | + } |
| 42 | + }, []); |
| 43 | +} |
0 commit comments