Home > Enterprise >  click on firstElementChild in react?
click on firstElementChild in react?

Time:07-07

I have this code

console.log(RefOfList.current.firstElementChild)

and I'm able to see the correct node printed. But how to I click it programmatically?

this won't work: RefOfList.current.firstElementChild.click() I got Property 'click' does not exist on type 'Element

CodePudding user response:

You may be interested in trying Selenium.

The following should work:

WebDriver driver = new FirefoxDriver(); //you can use whichever driver though
JavascriptExecutor jsDriver= (JavascriptExecutor)driver;
jsDriver.executeScript("document.getElementById('<id of element>').click();")

CodePudding user response:

I'm assuming this is a TypeScript question. If you know what kind of element the children beforehand, you can verify the tag name of the firstChild then type assert it.

For example,

import { useRef, useState } from "react";
import "./styles.css";

export default function App() {
  const parent = useRef<HTMLDivElement>(null);
  const [num, setNum] = useState(0);

  const onH2Click = () => {
    const firstChild = parent.current?.firstElementChild;

    if (firstChild?.tagName === "BUTTON") { 
      // if firstChild is not null and is a button
      (firstChild as HTMLButtonElement).click(); // Hey, this is a Button!
    }
  };

  return (
    <div className="App" ref={parent}>
      <button onClick={() => setNum(num   1)}>Click Me</button>
      <h2 onClick={onH2Click}>{num}</h2>
    </div>
  );
}

CodePudding user response:

Access the children of the current node. That is an array of elements. It's as easy as calling click() on the 0 index of the children array.

import { useEffect, useRef } from 'react'

export default function App() {
  const elem = useRef()

  useEffect(() => {
    elem.current.children[0].click()
  })
  
  return (
    <div className="App" ref={elem}>
      <h1 onClick={() => console.log("clicked")}>I'm clickable</h1>
      <h2>I'm the second element</h2>
    </div>
  );
}
  • Related