next js active link
To create an active link in Next.js, you can follow these steps:
- Import the
Link
component from thenext/link
module:
import Link from 'next/link';
- Use the
Link
component to wrap the anchor (<a>
) tag that represents the link:
<Link href="/path/to/page">
<a>Link Text</a>
</Link>
Replace /path/to/page
with the actual path to the page you want to link to, and replace Link Text
with the text you want to display as the link.
- Add the
active
class to the link when it is active. You can use theuseRouter
hook fromnext/router
to get information about the current route, such as the pathname. Then, you can conditionally apply theactive
class based on the current pathname:
import { useRouter } from 'next/router';
function MyLink() {
const router = useRouter();
return (
<Link href="/path/to/page">
<a className={router.pathname === '/path/to/page' ? 'active' : ''}>
Link Text
</a>
</Link>
);
}
Replace /path/to/page
with the actual path to the page you want to link to, and replace Link Text
with the text you want to display as the link.
- Style the
active
class in your CSS to visually indicate that the link is active:
a.active {
/ Your active link styles here /
}
By following these steps, you can create an active link in Next.js that highlights when the corresponding page is active.