Learnitweb

Programmatically trigger click event in react

To programmatically trigger a click event in React, you can use the useRef hook to reference a DOM element or component, and then call its .click() method.

Here’s a complete example:

Example: Programmatically triggering a button click

import React, { useRef } from 'react';

function App() {
  const buttonRef = useRef(null);

  const handleClick = () => {
    alert('Button was clicked!');
  };

  const triggerClick = () => {
    if (buttonRef.current) {
      buttonRef.current.click(); // Programmatically triggers the click
    }
  };

  return (
    <div>
      <button ref={buttonRef} onClick={handleClick}>
        Click Me
      </button>
      <button onClick={triggerClick}>
        Trigger Click Programmatically
      </button>
    </div>
  );
}

export default App;

Explanation:

  • useRef(null) creates a reference to the first button.
  • ref={buttonRef} attaches the reference to the actual button DOM element.
  • When the second button is clicked, it programmatically triggers .click() on the referenced button.