Skip to content

Commit ba34098

Browse files
committed
fix hydration issue with media queries
1 parent 0b94574 commit ba34098

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/components/MediaQuery.tsx

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"use client"
2+
3+
import { type ReactNode } from "react"
4+
5+
import { useMediaQuery } from "@/hooks/useMediaQuery"
6+
7+
type MediaQueryChildren =
8+
| ((args: { matches: boolean[]; any: boolean }) => ReactNode)
9+
| ReactNode
10+
11+
type MediaQueryProps = {
12+
/**
13+
* Array of CSS media query strings, e.g. ["(min-width: 768px)"]
14+
*/
15+
queries: string[]
16+
/**
17+
* Optional SSR fallbacks for each query. If omitted, defaults to false.
18+
*/
19+
fallbackMatches?: boolean[]
20+
/**
21+
* Either render props or slot children
22+
*/
23+
children: MediaQueryChildren
24+
}
25+
26+
const MediaQuery = ({
27+
queries,
28+
fallbackMatches,
29+
children,
30+
}: MediaQueryProps) => {
31+
const matches = useMediaQuery(queries, fallbackMatches)
32+
const any = matches.some(Boolean)
33+
34+
if (typeof children === "function") {
35+
return <>{children({ matches, any })}</>
36+
}
37+
38+
return <>{any ? children : null}</>
39+
}
40+
41+
export default MediaQuery

src/components/Nav/index.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import { getTranslations } from "next-intl/server"
22

33
import { EthHomeIcon } from "@/components/icons"
44

5+
import { breakpointAsNumber } from "@/lib/utils/screen"
6+
57
import ClientOnly from "../ClientOnly"
8+
import MediaQuery from "../MediaQuery"
69
import { BaseLink } from "../ui/Link"
710

811
import DesktopNav from "./DesktopNav"
@@ -28,10 +31,14 @@ const Nav = async () => {
2831

2932
<div className="ms-3 flex w-full justify-end md:justify-between xl:ms-8">
3033
<ClientOnly fallback={<DesktopNavLoading />}>
31-
<DesktopNav className="hidden md:flex" />
34+
<MediaQuery queries={[`(min-width: ${breakpointAsNumber.md}px)`]}>
35+
<DesktopNav />
36+
</MediaQuery>
3237
</ClientOnly>
3338
<ClientOnly fallback={<MobileNavLoading />}>
34-
<MobileNav className="flex md:hidden" />
39+
<MediaQuery queries={[`(max-width: ${breakpointAsNumber.md - 1}px)`]}>
40+
<MobileNav />
41+
</MediaQuery>
3542
</ClientOnly>
3643
</div>
3744
</nav>

0 commit comments

Comments
 (0)