Created
March 30, 2022 12:18
-
-
Save iuzn/23da621995ed73ffbcfb9ff50336c2dd to your computer and use it in GitHub Desktop.
In this example, I tried to show how to manipulate the 'hydration warning' that can be encountered in server-side rendering with React. Since the HTML code will match exactly on the server and client sides, such a warning will no longer appear.
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 { useRouter } from 'next/router' | |
import React, { useEffect, useState } from 'react' | |
import type { PropsWithChildren } from 'react' | |
interface MenuProps { | |
title: string | |
path: string | |
} | |
function MenuItem({ menu }: { menu: MenuProps }) { | |
const router = useRouter() | |
const [hasMounted, setHasMounted] = useState(false) | |
useEffect(() => { | |
setHasMounted(true) | |
}, []) | |
if (!hasMounted) { | |
return null | |
} | |
const isActive = | |
router.asPath.split('/')[1] === menu.path.split('/')[1] || | |
router.asPath === menu.path | |
const colorClass = isActive ? 'selected' : 'unselected' | |
return <a className={`${colorClass} link-class`}>{menu.title}</a> | |
} | |
export default function Layout({ children }: PropsWithChildren<{}>) { | |
const MENU = [ | |
{ | |
title: 'Home', | |
path: '/', | |
}, | |
{ | |
title: 'Blog', | |
path: '/blog', | |
}, | |
{ | |
title: 'About', | |
path: '/about', | |
}, | |
{ | |
title: 'Contact', | |
path: '/contact', | |
}, | |
] | |
return ( | |
<div className="layout-class"> | |
<header className="header-class"> | |
<nav className="nav-class"> | |
{MENU.map((item, index) => ( | |
<MenuItem key={index} menu={item} /> | |
))} | |
</nav> | |
</header> | |
<div className="content-class">{children}</div> | |
<footer className="footer-class">{'...footer'}</footer> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment