最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hyperlink - How can I give a Next.JS (app router) <Link> component some extra behavior before it navigates? - Stac

programmeradmin2浏览0评论

My use case can be described like this:

  • I have an app with a sidebar.
  • The sidebar has links to functionality related to each particular "item".
  • I have a way that can record which "item" has been selected so that the later sidebar renders (when you are working on things for that "item") can remind you of which "item" we are on.
  • Later on, when the user returns or leaves or whatever (obviously app specific) I need to turn off this indication.

The recording, and on/off mechanisms are pretty clear (use a React context, with or without persistent LocalStorage updates if you need that).

What is not obvious is how I can make a NextJS component execute my extra logic to do the on/off switching, before it does the requested navigation.

Yes, I could use raw "a" tags, but that causes complete refreshes, and eliminates the opportunity to use anything else that "Link" does for me.

Is there anyway to provide a "before you navigate, do this (whatever) type of thing"?

My use case can be described like this:

  • I have an app with a sidebar.
  • The sidebar has links to functionality related to each particular "item".
  • I have a way that can record which "item" has been selected so that the later sidebar renders (when you are working on things for that "item") can remind you of which "item" we are on.
  • Later on, when the user returns or leaves or whatever (obviously app specific) I need to turn off this indication.

The recording, and on/off mechanisms are pretty clear (use a React context, with or without persistent LocalStorage updates if you need that).

What is not obvious is how I can make a NextJS component execute my extra logic to do the on/off switching, before it does the requested navigation.

Yes, I could use raw "a" tags, but that causes complete refreshes, and eliminates the opportunity to use anything else that "Link" does for me.

Is there anyway to provide a "before you navigate, do this (whatever) type of thing"?

Share Improve this question edited Mar 15 at 2:51 Craig McClanahan asked Mar 15 at 2:45 Craig McClanahanCraig McClanahan 1791 gold badge1 silver badge7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Found the answer, courtesy of GitHub Copilot:

To execute custom logic before navigation, you can wrap the next/link component with a custom component and handle the logic within that component.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论