Created
August 30, 2024 11:40
-
-
Save p32929/e8abdbbabce1b499400b56f59b09d815 to your computer and use it in GitHub Desktop.
This file contains 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 { useState, useEffect } from 'react'; | |
const breakpoints = { | |
// sm: 640, | |
// md: 768, | |
lg: 1024, | |
// xl: 1280, | |
}; | |
const getBreakpoint = (width) => { | |
// if (width >= breakpoints.xl) return 'xl'; | |
if (width >= breakpoints.lg) return 'lg'; | |
// if (width >= breakpoints.md) return 'md'; | |
// if (width >= breakpoints.sm) return 'sm'; | |
return 'default'; | |
}; | |
const useBreakpoint = () => { | |
const [breakpoint, setBreakpoint] = useState(() => { | |
// Check if window is defined to avoid server-side rendering issues | |
if (typeof window !== 'undefined') { | |
return getBreakpoint(window.innerWidth); | |
} | |
return 'default'; | |
}); | |
useEffect(() => { | |
// Only run the effect on the client | |
if (typeof window !== 'undefined') { | |
const handleResize = () => { | |
setBreakpoint(getBreakpoint(window.innerWidth)); | |
}; | |
window.addEventListener('resize', handleResize); | |
// Initial setting of breakpoint | |
handleResize(); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
} | |
}, []); | |
return breakpoint; | |
}; | |
export default useBreakpoint; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment