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

javascript - Next.js execute onClick event before href link routing - Stack Overflow

programmeradmin0浏览0评论

Context

I'm using Next.js 13. And I'm using apollo client to store some client side variables.

What i'm trying to do

I'm trying to execute the onClick function prior to navigating to the href location.

My Code

<Link
      href={`/session/${session.id}`}
      onClick={() => {            
        updateDialogVars({
          dialogOpen: ATTENDANCE_DIALOG,
        })
      }}
    >
    <div>
      stuff
    </div>
</Link>

updateDialogVars is a mutation and updates a reactive vars in apollo client.

Question

Is it possible to use Next.js Link ponent and execute the onClick event before routing takes place with the href? Is the only option to change Link to a div and use next router to push the route change after the onClick function executes?

Context

I'm using Next.js 13. And I'm using apollo client to store some client side variables.

What i'm trying to do

I'm trying to execute the onClick function prior to navigating to the href location.

My Code

<Link
      href={`/session/${session.id}`}
      onClick={() => {            
        updateDialogVars({
          dialogOpen: ATTENDANCE_DIALOG,
        })
      }}
    >
    <div>
      stuff
    </div>
</Link>

updateDialogVars is a mutation and updates a reactive vars in apollo client.

Question

Is it possible to use Next.js Link ponent and execute the onClick event before routing takes place with the href? Is the only option to change Link to a div and use next router to push the route change after the onClick function executes?

Share asked Mar 7, 2023 at 2:12 NickNick 2958 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

This is typically achieved with a button and router hook, not an anchor tag (link).

import { useRouter } from "next/router"; // if you use pages dir
import { useRouter } from "next/navigation"; // if you use app dir

const SomeComponent = () => {
 const router = useRouter();

 const onClick = async () => {
  updateDialogVars(...yourConfig);
  if(someCondition) {
   await router.push(`/session/${session.id}`);
  }
 }

 return (
  <button onClick={onClick}>Label</button>
 )
}

You can also achieve a similar result with next/link.

import { useRouter } from "next/router"; // if you use pages dir
import { useRouter } from "next/navigation"; // if you use app dir
import Link from "next/link";

const SomeComponent = () => {
 const router = useRouter();

 const onClick = async (event) => {
  event.preventDefault();
  updateDialogVars(...yourConfig);
  if(someCondition) {
   await router.push(event.target.href);
  }
 }

 return (
  <Link href={`/session/${session.id}`} onClick={onClick}>Label</Link>
 )
}
发布评论

评论列表(0)

  1. 暂无评论