Skip to content

Commit 5b5177d

Browse files
authored
[polaris.shopify.com] Fix next.js rehydration issue (#7922)
Fixes this annoying message in development: <img width="1011" alt="image" src="https://user-images.githubusercontent.com/875708/207904298-8ebb19c3-3b9d-43cf-8a1a-78939a3f6b1a.png"> It was caused by the dark mode switcher having different states between the server and the client, thus breaking rehydration. This fix ensures that the dark mode toggle is only rendered on the client.
1 parent 5025305 commit 5b5177d

File tree

1 file changed

+12
-7
lines changed
  • polaris.shopify.com/src/components/Frame

1 file changed

+12
-7
lines changed

polaris.shopify.com/src/components/Frame/Frame.tsx

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ function Frame({darkMode, children}: Props) {
2828
const menuButtonRef = useRef<HTMLButtonElement>(null);
2929
const closeButtonRef = useRef<HTMLButtonElement>(null);
3030
const {asPath} = useRouter();
31+
const [isMounted, setIsMounted] = useState(false);
32+
33+
useEffect(() => setIsMounted(true), []);
3134

3235
useEffect(() => {
3336
const mainContent = document.querySelector('#main');
@@ -120,13 +123,15 @@ function Frame({darkMode, children}: Props) {
120123
Polaris
121124
</Link>
122125

123-
<button className={styles.DarkModeToggle} onClick={darkMode.toggle}>
124-
{darkMode.value ? (
125-
<div className={styles.LightModeIcon}>💡</div>
126-
) : (
127-
<div className={styles.DarkModeIcon}>🌙</div>
128-
)}
129-
</button>
126+
{isMounted && (
127+
<button className={styles.DarkModeToggle} onClick={darkMode.toggle}>
128+
{darkMode.value ? (
129+
<span className={styles.LightModeIcon}>💡</span>
130+
) : (
131+
<span className={styles.DarkModeIcon}>🌙</span>
132+
)}
133+
</button>
134+
)}
130135

131136
<GlobalSearch />
132137
</div>

0 commit comments

Comments
 (0)