Next.js triggers the onClick event before routing to the href link

Scenario

In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables.

Objective

I aim to trigger the onClick function before navigating to the href location.

The Code I'm Using

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

The updateDialogVars method is a mutation that updates reactive vars in Apollo Client.

Inquiry

Is it feasible to leverage the Next.js Link component to execute the onClick event prior to routing to the href? Or should I convert the Link to a div and employ Next Router to push the route change after executing the onClick function?

Answer №1

In order to achieve this functionality, it is recommended to use a button along with a router hook, instead of 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>
 )
}

A similar outcome can also be achieved using 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>
 )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validation using Joi allows for a field to be optional, but if it is included, it must be a positive integer

I am facing a challenge with a field in my JOI schema that I want to make optional, allowing for both undefined and null values. However, if a value is provided, it must be a positive integer. How can I accomplish this? So far, I have attempted the follow ...

Tips for obtaining the dynamically loaded HTML content of a webpage

I am currently attempting to extract content from a website. Despite successfully obtaining the HTML of the main page using nodejs, I have encountered a challenge due to dynamic generation of the page. It seems that resources are being requested from exter ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...

The issue with sentry's captureException is that it only displays part of the

When handling errors in my NextJS app, I use captureException(error); within a catch block. However, I've noticed that Sentry doesn't display the full error message like it does in the developer console. Instead, it only shows something like: Ax ...

Utilizing HIGHCHARTS to effectively access PHP variables from a separate PHP file through Jquery/Ajax

I am facing an issue with accessing PHP variables from my main page in a PHP file called by AJAX. Is there a way to access these variables or should I include the PHP file in the one called by AJAX? PHP : variables.php <?php $myServername = "loca ...

Combine loop results into a string using jQuery

When using jQuery, I need to append a multiline string to an element by adding a string return from each value in a for loop. $("songs-table-tr").append('tr id="songs-table-tr'+count+'" style="display: none">\ ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

Unable to dynamically attach a class in Vue.js

I have exhausted all possible variations of this issue. I meticulously followed the official Vue guides, consulted numerous stack overflow posts, and went through various tutorials. I experimented with different syntaxes, quotations, array structures, and ...

creating a countdown timer for the carousel

While experimenting, I decided to create a basic carousel from scratch. Initially, I used onclick="function()" to cycle through the images. Later on, I attempted to replace it with onload="setInterval(function, 4000)", but it seems like something went wron ...

Guide on configuring Angular validation to trigger on blur events and form submission

Validation in Angular is currently set to update on model change, but this method can be unfriendly for user interface as it displays errors upon keyup. An optimal solution would involve displaying error messages on blur and also on form submission. After ...

The JSX syntax was not properly parsed by Jest despite correct configuration settings

After setting up a new Next.js project and configuring jest and testing library as instructed, I encountered a syntax error causing my test to fail. It seems that ts-jest is having trouble parsing stayles.container for some reason. What could be the cause ...

Utilizing environmental variables with cPanel in Node.js

Currently, I am utilizing cPanel in combination with the Setup Node.js App plugin to run a Next.js application. (Please don't inquire about my choice of cPanel) During development, everything seems to be functioning correctly except for the handling ...

Unable to execute specific php function using ajax

I have created a script that utilizes an ajax request. This script is triggered when a user clicks a button on the index.php page, like so: Risorse.php <form method='post'> Name <input type='text' name='nome&apo ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Expired Azure app registration client secret leads to CORS error when accessing API

My current setup involves a backend built with ASP.net and a frontend application using NextJS. Authentication is handled through Azure AD. Recently, I have been encountering CORS errors on my API. Upon investigation, I discovered that a "client secret" h ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Show a loading progress indicator with a percentage until Next/React completes loading

For my upcoming SPA project, I will be fetching a 3D map and data from an API. Is there a method to incorporate a loading banner that displays the current percentage of files, components, or data loaded before the application is completely loaded? I am in ...

Alternate Row Colors Using Odd/Even CSS Styling for Main Headings

In my expand/collapse table, I have set up alternating row colors (dark grey and light grey) that adjust automatically when expanding or collapsing. The challenge I'm facing is that for certain rows, I want to apply a specific background color using ...