[英]How to track active link in next.js?
I have a sidebar component in my admin panel which has multiple links.我的管理面板中有一个侧边栏组件,它有多个链接。 Some of these links are in the dropdown menu.
其中一些链接位于下拉菜单中。 Now I want to add an active class based on an active link or if the active link is in the dropdown menu then to the dropdown toggle.
现在我想添加一个基于活动链接的活动类,或者如果活动链接在下拉菜单中,则添加到下拉切换。 Below is my code for a sidebar.
下面是我的侧边栏代码。 Btw I am using antd framework for ui.
顺便说一句,我正在为 ui 使用 antd 框架。
<Sider
width={260}
className={styles.sider}
collapsible
trigger={null}
collapsed={drawer}
breakpoint={"md"}
collapsedWidth={0}
>
<Menu mode="inline">
<Menu.Item
icon={<IoGrid />}
key="1"
onClick={(e) => {
toggleKey(e);
gotoPage("/");
}}
className={selectedKey == 1 ? styles.active_item : ""}
>
Dashboard
</Menu.Item>
<SubMenu
title="Settings"
key="2"
icon={<IoSettingsOutline />}
className={selectedKey == 2 ? styles.active_item : ""}
>
<Menu.Item
icon={<IoPersonAddOutline />}
key="2.1"
onClick={(e) => {
toggleKey(e);
gotoPage("/settings/profile");
}}
>
Profile
</Menu.Item>
</SubMenu>
</Menu>
</Sider>
Btw the selectedKey and toggleKey function comes from top level component and gotoPage is just router.push functionality.顺便说一句, selectedKey 和 toggleKey 功能来自顶级组件,而 gotoPage 只是 router.push 功能。
Thanks.谢谢。
As per this answer you should use useRouter
hook to get current path.根据这个答案,您应该使用
useRouter
hook 来获取当前路径。
For your use case instead of equality check you should probably use startsWith
or maybe some other check.对于您的用例而不是等式检查,您可能应该使用
startsWith
或其他一些检查。 So it would look like this所以它看起来像这样
Let's say you have假设你有
Settings -> /settings
Profile -> /settings/profile
Notifications /settings/notifications
You check if current path starts /settings
and you assume that Settings group is active and you simply expand Settings submenu and add active class to Settings group.您检查当前路径是否以
/settings
开头,并假设 Settings 组处于活动状态,您只需展开 Settings 子菜单并将活动类添加到 Settings 组。
If you are currently on /settings/notification
this would mean that you can identify following:如果您当前在
/settings/notification
这意味着您可以识别以下内容:
I think it is better to have custom LinkGroup
component that would check for its 'activeness' and would add specific styling and show/hide its submenu.我认为最好使用自定义
LinkGroup
组件来检查其“活动性”并添加特定样式并显示/隐藏其子菜单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.