Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can fire the click event button automatically

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div className="field">
    <div className="control">
        <button type="button" onClick={downloadHandler} className="btn-small">
             Download
        </button>
    </div>
</div>

>Solution :

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
}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading