0
votes

I have a <tr> that contains multiple <td>'s. Each <td> has a click event but I would like to programmatically click through React useRef hook or any other hook that can achieve my goal.

Since all <td>'s share the same className, I can trigger the click event through the DOM as per below:

document.getElementsByClassName('cell')[cellNumber].click()

// Example: to trigger the click of first cell:
// document.getElementsByClassName('cell')[0].click()

Sample Code - I tried assigning a shared ref cellRef :

export const Row = ({ props }) => {
  const cellRef = useRef(null)

  return (
    <tr>
      {row.map((c, i) => (
        <td
          className="cell"
          ref={cellRef}
          onClick={handleCell}
        >
        </td>
        ))}
    </tr>
  )
}

Below only triggers the last <td>, I want to choose the cell number:

cellRef.current.click()
Does the cell have to actually be clicked or can you just call handleCell many times? - windowsill
@windowsill The goal is to have it clicked by mouse which already works, and also programmatically from other sources. Obviously using the DOM does the job, but wondering if there is a recommended ReactJS approach. - Abdulelah