How to programmatically trigger click event in react

How to Programmatically Trigger Click Event in React

In React, you can programmatically trigger a click event on an element by using the ref attribute and the click() method. Here is an example:

    
      import React, { useRef } from 'react';

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

        const handleClick = () => {
          console.log('Button clicked!');
        }

        const handleProgrammaticClick = () => {
          buttonRef.current.click();
        }

        return (
          
); } export default App;

In this example, we create a functional component App that renders two buttons. The first button has a ref attribute set to buttonRef and an onClick event handler handleClick. The second button triggers the handleProgrammaticClick event handler when clicked.

Inside the handleProgrammaticClick function, we call the click() method on the buttonRef.current to programmatically trigger the click event on the first button. This will effectively call the handleClick function and log “Button clicked!” to the console.

By using the ref attribute and the click() method, we can programmatically trigger click events in React components.

Leave a comment