javascriptnext.jsautomation

Use external js to trigger click event in Next.js component


I've been tasked with making some manual updates in a UI that was built with Next.js. There is an element in the UI that repeats about 1 million times (not really but you get the idea) and I need to click the element to toggle the state.

The selector for the element is easy. I wrote const el = document.querySelector('some-selector') in the console and was able to log out the correct element. Only problem is that when I execute el.click() the element state is not toggled. I also tried el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: false })); with no luck.

For example, I believe Nike's website uses Next.js. If you go to the home page and open the console, you can select the swoosh icon with this: const swoosh = document.querySelector('.swoosh'). What I need to is to simulate a click on that element from the console.

I assume the problem here is that under the hood, the next.js component has a custom click handler and for whatever reason it is not being triggered unless I physically click the element. Anyone know how I can call the actual next.js click handler with code?


Solution

  • This is probably not about next.js specifically, this seems more of a React problem. The case that you face with your own project and the one in the Nike website you provide could also be different. But to trigger the one in the Nike website, we could at least do this:

    const swooshAnchor = document.querySelector('.swoosh a');
    function getReactProps(el) {
      const keys = Object.keys(el);
      const propKey = keys.find(key => key.includes('reactProps'));
      return el[propKey];
    }
    
    getReactProps(swooshAnchor).onClick(new Event('click'));
    

    You first need to identify which element has the onClick listener attached exactly (in this case it's the <a> element, which is the child of .swoosh, and in your case, it might be something else). Then what the above code does is basically get the react props from the element, and get the onClick function inside it.