Implementing a dynamic sidebar navigation in Next.js involves creating a component for the sidebar and managing its state to render the navigation items dynamically. Here's a step-by-step guide on how to do it:
jsx// components/Sidebar.js
import { useState } from 'react';
const Sidebar = () => {
const [activeItem, setActiveItem] = useState(null);
const handleItemClick = (itemName) => {
setActiveItem(itemName);
// Add logic to handle item click, such as navigating to a different page
};
return (
<div className="sidebar">
<ul>
<li className={activeItem === 'Home' ? 'active' : ''} onClick={() => handleItemClick('Home')}>Home</li>
<li className={activeItem === 'About' ? 'active' : ''} onClick={() => handleItemClick('About')}>About</li>
{/* Add more navigation items dynamically */}
</ul>
</div>
);
};
export default Sidebar;
Sidebar
component in your layout or page components where you want to display the sidebar.jsx// pages/_app.js or layout component
import Sidebar from '../components/Sidebar';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return (
<div className="app">
<Sidebar />
<Component {...pageProps} />
</div>
);
}
export default MyApp;
css/* styles/globals.css */
.sidebar {
width: 200px;
background-color: #f0f0f0;
}
.sidebar ul {
list-style-type: none;
padding: 0;
}
.sidebar li {
padding: 10px;
cursor: pointer;
}
.sidebar li:hover {
background-color: #ddd;
}
.sidebar li.active {
font-weight: bold;
color: #0070f3;
}
getStaticProps
or getServerSideProps
to fetch the data and pass it as props to the Sidebar
component.That's it! You've now implemented a dynamic sidebar navigation in Next.js. You can extend this further by adding more features like nested navigation, collapsible sidebar, or integration with client-side routing libraries like Next.js's built-in Link
component for smoother navigation transitions.