'I have a qr code maker. Wanted to ask how I can download it as a direct download in react
So I made a qr code generator. The user inputs a string that is then turned into a qr code. The download button takes me to another website where im guessing the user should right click and press save image as etc etc. I dont want it to do that. I want it to directly download when I press the download button.
import { useEffect, useState } from 'react';
import './App.css';
function App() {
const [temp, setTemp] = useState("");
const [word, setWord] = useState("");
const [qrCode, setQrCode] = useState("");
// Changing the URL only when the user
// changes the input
useEffect(() => {
setQrCode
(`http://api.qrserver.com/v1/create-qr-code/?data=${word}`);
}, [word]);
// Updating the input word when user
// click on the generate button
function handleClick() {
setWord(temp);
}
return (
<div className="App">
<div className="input-box">
<div className="gen">
<input type="text" onChange={
(e) => {setTemp(e.target.value)}}
placeholder="Enter text to encode" />
<button className="button"
onClick={handleClick}>
Generate
</button>
</div>
</div>
<div className="output-box">
<img src={qrCode} alt="" />
<a href={qrCode} download="QRCode">
<button type="button">Download</button>
</a>
</div>
</div>
);
}
export default App;
Seen below is where it takes me to download the image: enter image description here
Solution 1:[1]
You can try to add something like this to your component:
async function load() {
if (!!qrCode) {
try {
const image = await fetch(qrCode);
const imageBlob = await image.blob();
const bURL = URL.createObjectURL(imageBlob);
const anchor = document.createElement("a");
anchor.href = bURL;
anchor.target = "_blank";
anchor.download = "qr.png";
// Auto click on a element, trigger the file download
anchor.click();
// This is required
URL.revokeObjectURL(bURL);
} catch (err) {
console.log(err);
}
}
}
// and your button can do that onClick
<button onClick={load}>Download</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ikos23 |
