Sometimes, we want to manually trigger a click event in React.
In this article, we’ll look at how to manually trigger a click event in React.
How to manually trigger a click event in React?
To manually trigger a click event in React, we assign a ref to the element we want to trigger the click on.
Then we call click
on the ref’s current
property.
For instance, we write
const UploadsWindow = () => {
const inputFile = useRef();
const uploadClick = (e) => {
e.preventDefault();
inputFile.current.click();
return false;
};
return (
<>
<input type="file" name="fileUpload" ref={inputFile} multiple />
<a href="#" className="btn" onClick={uploadClick}>
Add or Drag Attachments Here
</a>
</>
);
};
to create the inputFile
ref with the useRef
hook.
Then we assign it as the value of the ref
prop of the file input.
Next, we call inputFile.current.click
to trigger a click on the file input in the uploadClick
function.
Conclusion
To manually trigger a click event in React, we assign a ref to the element we want to trigger the click on.