Next.js ์ด์ฉํ ํ๋ก์ ํธ์์ ๋ค๋น๊ฒ์ด์ ๋ฐ๋ฅผ ๊ตฌํํ๋ ์ค ์๋์ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ์๋ค.
[์๋ฌ๊ฐ ๋ฐ์ํ ์ปดํฌ๋ํธ ์ฝ๋ ์ผ๋ถ]
import styled from '@emotion/styled';
import Link from 'next/link';
import { useRouter } from 'next/router';
const Navbar = () => {
const router = useRouter();
const { pathname } = router;
return (
<nav>
<ul>
{NAVIGATION_LIST.map((navigation) => {
const { label, href } = navigation;
// pathname๊ณผ href๊ฐ ๋์ผํ์ง ํ์ธ
// ํ์ฌ ๊ฒฝ๋ก๊ฐ ์ ํํ ๋ค๋น๊ฒ์ด์
๋ฉ๋ด์ ๋์ผํ ๋ active css ์ ์ฉ
const isActive = pathname.match(href) !== null;
return (
<li key={`navigation-${label}`}>
<!-- Link์ isActive๋ฅผ ์ถ๊ฐํ์ฌ css ์ ์ฉ -->
<NavigationLink href={href} isActive={isActive}>
<span>{label}</span>
</NavigationLink>
</li>
);
})}
</ul>
</nav>
);
};
export default Navbar;
const NavigationLink = styled(Link)`
// ์ฝ๋ ์๋ต
color: ${({ theme, isActive }) =>
isActive ? theme.colors.main : theme.colors.gray_999};
`;
Link
Link
์ปดํฌ๋ํธ๋ฅผ ํตํด ๋์ํ ์ ์๋ค.<a>
ํ๊ทธ ๋์ <Link>
๋ฅผ ์ฌ์ฉLink
์ปดํฌ๋ํธ๋ ํน์ ์์ฑ๋ง ๋ฐ๋ HOC(Higher Order Component)์ด๋ค.Link
์ปดํฌ๋ํธ ์ง์ ๋ ์์ฑ์ด ์๋ ๋ค๋ฅธ ์์ฑ์ ์ถ๊ฐํ๋ฉด ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.link.d.ts
์ InternalLinkProps
์ ํด๋นํ๋ ์์ฑ๋ค๋ง ์ฌ์ฉํ ์ ์๋ค.Link
์ปดํฌ๋ํธ์ ์ ์ฉํ ์์ฑ์ ๋ค๋ฅธ ํ๊ทธ์ ์ ์ฉํ์ฌ ํด๊ฒฐ[์์ ํ ์ฝ๋]
import styled from '@emotion/styled';
import Link from 'next/link';
import { useRouter } from 'next/router';
const Navbar = () => {
const router = useRouter();
const { pathname } = router;
return (
<nav>
<ul>
{NAVIGATION_LIST.map((navigation) => {
const { label, href } = navigation;
const isActive = pathname.match(href) !== null;
return (
<li key={`navigation-${label}`}>
<!-- Link์ isActive ์์ฑ ์ญ์ -->
<NavigationLink href={href}>
<!-- Label์ isActive ์์ฑ ์ ์ฉ -->
<Label isActive={isActive}>{label}</Label>
</NavigationLink>
</li>
);
})}
</ul>
</nav>
);
};
export default Navbar;
// Label์ isActive๋ฅผ ์ ๋ฌํ์ฌ active css ์ ์ฉ
const Label = styled.span<{ isActive: boolean }>`
color: ${({ theme, isActive }) =>
isActive ? theme.colors.main : theme.colors.gray_999};
`;
์ฐธ๊ณ