I want to create a download button which will download image from api, I was able to do that but then got stuck in a problem . whenever I click on download button it does download the image but it also open the image in that page which makes it to leave the main page. I want it so that it won't open the image only download the image .
here is what I did
const download = (e) => {
console.log(e.target.href);
fetch(e.target.href, {
method: "GET",
headers: {},
})
.then((response) => {
response.arrayBuffer().then(function (buffer) {
const url = window.URL.createObjectURL(new Blob([buffer]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "image.png"); //or any other extension
document.body.appendChild(link);
link.click();
});
})
.catch((err) => {
console.log(err);
});
};
<div className="row">
<div className="col-sm-4 text-center">
{quote?.map((items) => (
<div class="card" style={{ width: "18rem;" }}>
<img src={items.img} class="card-img-top" alt="..." />
<div class="card-body">
<h5 style={{ textTransform: "capitalize" }} class="card-title">
{items.name.replace(/_/g, " ")}
</h5>
<p class="card-text">{items.disc}</p>
<Button
variant="outlined"
href={items.img}
onClick={ download }
>
Download
</Button>
</div>
</div>
))}
</div>
</div>