0

I am creating a geography game where you are supposed to click on a specific country on a world map - if you click on the right one, the country changes color and the game presents a new country to be clicked at. If the player doesn't know, he can click on a button which will show him the correct answer. For this, I want to simulate a click event, so that the same onClick() function is called as if you clicked on the correct country.

I am using D3, and the world map is made up of svg paths. Below is the code I thought would work, using the HTMLElement.click() method:

    function simulateClick() {

    // for each index in the nodelist, 
    // if the properties are equal to the properties of currentTargetUnit,
    // simulate a click on the path of that node

    let nodelist = d3.selectAll(".unit")
    for (let i = 0; i < nodelist._groups[0].length; i++) {
        if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
            console.log(nodelist._groups[0][i])
            // logs the correct svg path element
            nodelist._groups[0][i].click()
            // logs TypeError: nodelist._groups[0][i].click is not a function
        }
    }
}

I then looked at some tutorials which say that, for some reason I don't fully understand, you rather need to use React.useRef for this - but in all their examples, they put a "ref" value on an element which is returned from the beginning in the React component, like so:

import React, { useRef } from "react";

const CustomTextInput = () => {
  const textInput = useRef();

  focusTextInput = () => textInput.current.focus();

  return (
    <>
      <input type="text" ref={textInput} />
      <button onClick={focusTextInput}>Focus the text input</button>
    </>
  );
}

This obviously doesn't work because my svg path elements aren't returned initially. So my question is - how can I achieve this, whether using useRef or not?

Below are some previous questions I looked at which also did not help. Simulate click event on react element React Test Renderer Simulating Clicks on Elements Simulating click on react element

Zuzim
  • 75
  • 4
  • 12

1 Answers1

1

I finally solved it - instead of calling the onClick() which was set inside the node I created a new clickevent with the help of the following code:

    function simulateClick() {
    let nodelist = d3.selectAll(".unit")
    for (let i = 0; i < nodelist._groups[0].length; i++) {
        if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
            var event = document.createEvent("SVGEvents");
            event.initEvent("click",true,true);
            nodelist._groups[0].item(i).dispatchEvent(event);
        }
    }
}
Zuzim
  • 75
  • 4
  • 12