In React, you can manually trigger a click event by either calling the click()
method on the DOM element or by using the synthetic event system provided by React.
To do this, we
Using click()
method on the DOM element:
import React, { useRef } from 'react';
function MyComponent() {
const buttonRef = useRef(null);
const handleClick = () => {
buttonRef.current.click(); // Manually trigger the click event
};
return (
<div>
<button ref={buttonRef} onClick={() => console.log("Button clicked")}>
Click me
</button>
<button onClick={handleClick}>Manually Trigger Click</button>
</div>
);
}
export default MyComponent;
In this example:
- We use the
useRef
hook to create a reference to the button element. - The
handleClick
function is triggered when the “Manually Trigger Click” button is clicked. - Inside
handleClick
, we call theclick()
method on the button’s ref to manually trigger its click event.
Using synthetic event system provided by React:
import React, { useRef } from 'react';
function MyComponent() {
const buttonRef = useRef(null);
const handleClick = () => {
buttonRef.current.dispatchEvent(new MouseEvent("click", { bubbles: true }));
};
return (
<div>
<button ref={buttonRef} onClick={() => console.log("Button clicked")}>
Click me
</button>
<button onClick={handleClick}>Manually Trigger Click</button>
</div>
);
}
export default MyComponent;
In this example, we use the useRef
hook to create a reference to the button element.
The handleClick
function is triggered when the “Manually Trigger Click” button is clicked.
Inside handleClick
, we use the dispatchEvent
method to create and dispatch a synthetic click event on the button element.
Both approaches will result in the onClick
handler of the button being called as if the button were clicked by the user.
Choose the one that suits your requirements and preferences.