Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Last active November 18, 2022 14:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugmanrique/4c9548078ae5d7e4252a7cec58ff2a06 to your computer and use it in GitHub Desktop.
Save hugmanrique/4c9548078ae5d7e4252a7cec58ff2a06 to your computer and use it in GitHub Desktop.
Next.js Navbar component using the new React Hooks API
import React, { useState, useEffect } from 'react';
import Router from 'next/router';
import Link from 'next/link';
export default function Navbar({ brand, items }) {
const [activeIndex, setActiveIndex] = useState(-1);
useEffect(
() => {
const handleRouteChange = url => {
const newActiveIndex = items.findIndex(item => item.url === url);
setActiveIndex(newActiveIndex);
};
Router.events.on('routeChangeComplete', handleRouteChange);
// Force first update
handleRouteChange(Router.route);
return () => Router.events.off('routeChangeComplete', handleRouteChange);
},
[items]
);
return (
<nav className="navbar">
<div className="brand">{brand}</div>
<div className="items">
{items.map((item, index) => (
<Link
href={item.url}
active={activeIndex === index ? 'active' : undefined}
key={item.id}
className="item"
>
{item.title}
</Link>
))}
</div>
</nav>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment