I have a download button in my page,I want to trigger it automatically when render to this page, how can I do that? I read some answers from Stack Overflow to useRef(), but I still do not quite understand how to apply it.
My download function:
const downloadHandler = async (e) => {
const getNewCategory = async () => {
await axios({
method: "GET",
url: "http://localhost:3001/download",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
setNCategory(res.data)
console.log("res.data: " JSON.stringify(res.data));
});
}
getNewCategory()
}
My button:
<div className="field">
<div className="control">
<button type="button" onClick={downloadHandler} className="btn-small">
Download
</button>
</div>
</div>
CodePudding user response:
Add an id to your button
<button id="download" type="button" onClick={downloadHandler} className="btn-small">
Then you can manually trigger click event
const downloadButton = document.getElementById('download');
downloadButton.dispatchEvent(new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
}));
Call it like above where you needed
UPDATE Using ref, here's the way
We define our ref
const downloadButton = useRef(null);
and use it on or button
<button ref={downloadButton} type="button" onClick={downloadHandler} className="btn-small">
then trigger click event
downloadButton.current.dispatchEvent(new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
}));