File tree 2 files changed +49
-0
lines changed
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ import useBreakpoints from "./useBreakpoints" ;
2
+
3
+ export default function BreakpointsComponent ( ) {
4
+ const { isMobile, isTablet } = useBreakpoints ( ) ;
5
+
6
+ return (
7
+ < >
8
+ { isMobile && < div > Mobile</ div > }
9
+ { isTablet && < div > Tablet</ div > }
10
+ </ >
11
+ ) ;
12
+ }
Original file line number Diff line number Diff line change
1
+ import { useState , useEffect } from "react" ;
2
+
3
+ const useBreakpoints = ( ) => {
4
+ const [ currentBreakpoint , setCurrentBreakpoint ] = useState ( "" ) ;
5
+
6
+ useEffect ( ( ) => {
7
+ const handleResize = ( ) => {
8
+ const mobileMatch = window . matchMedia ( "(min-width: 320px)" ) ;
9
+ const tabletMatch = window . matchMedia ( "(min-width: 768px)" ) ;
10
+ const desktopMatch = window . matchMedia ( "(min-width: 1024px)" ) ;
11
+
12
+ if ( desktopMatch . matches ) {
13
+ setCurrentBreakpoint ( "desktop" ) ;
14
+ } else if ( tabletMatch . matches ) {
15
+ setCurrentBreakpoint ( "tablet" ) ;
16
+ } else if ( mobileMatch . matches ) {
17
+ setCurrentBreakpoint ( "mobile" ) ;
18
+ }
19
+ } ;
20
+
21
+ handleResize ( ) ; // Initial check
22
+ window . addEventListener ( "resize" , handleResize ) ;
23
+ return ( ) => window . removeEventListener ( "resize" , handleResize ) ;
24
+ } , [ ] ) ;
25
+
26
+ const isMobile = currentBreakpoint === "mobile" ;
27
+ const isTablet = currentBreakpoint === "tablet" ;
28
+ const isDesktop = currentBreakpoint === "desktop" ;
29
+
30
+ return {
31
+ isMobile,
32
+ isTablet,
33
+ isDesktop,
34
+ } ;
35
+ } ;
36
+
37
+ export default useBreakpoints ;
You can’t perform that action at this time.
0 commit comments