0

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

  • Does this answer your question? [Download image with JavaScript](https://stackoverflow.com/questions/17311645/download-image-with-javascript) – Heretic Monkey Mar 19 '22 at 18:41
  • 1
    It is invalid in HTML to have a `button` inside an anchor (`a`). Style your anchor like a button if you want it to look like a button. – Heretic Monkey Mar 19 '22 at 18:43

1 Answers1

0

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>
ikos23
  • 4,879
  • 10
  • 41
  • 60