[英]How to get active link to work with dynamic sub paths in Next.js
I am using next/router to check for the current pathname and then conditionally rendering an active className.我正在使用 next/router 检查当前路径名,然后有条件地呈现一个活动的类名。
Here is what I am doing:这是我正在做的事情:
import { useRouter } from 'next/router';
const router = useRouter();
{
navigation.map((item) => (
<Link href={item.href}>
<a
key={item.name}
className={classNames(
router.pathname === item.href
? 'text-purple-700'
: 'text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white',
'px-3 py-2 text-base font-medium',
)}
aria-current={item.current ? 'page' : undefined}
>
{item.name}
</a>
</Link>
));
}
The issue is I'm also trying to display the active className for dynamic sub routes.问题是我还试图显示动态子路由的活动类名。 For example /item.href/{id}, so it could be /blog/1.
例如 /item.href/{id},所以它可能是 /blog/1。
Is it possible to achieve this?有可能实现这一目标吗?
It is possible, you can get the id from router params with有可能,您可以从路由器参数中获取 id
const {id} = router.query
then your matching condition to check the route然后你的匹配条件来检查路线
router.pathname === item.href.replace('[id]', id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.