Adding Logic to the QR Code Generator
The last part of the application is to add the logic for the generate button to be able to generate QR code and display in the output area. To do that, you do not need to create a separate file. We can achieve the logic by using useState()
, onClick()
and onChange()
functions we saw in the previous module.
Note: If you get any errors in importing the qrcode
module, try installing manually in the terminal using npm i qrcode
command.
- Add the logic to the QrGenerator component.
// QrGenerator.jsx
// Import the functions from the react package
import QRCode from "qrcode";
import { useState } from "react";
import "./QrGenerator.css";
function QrGenerator() {
// Create variables to track the changes in input and qrcode.
const [input, setInput] = useState("");
const [qrCode, setQrCode] = useState("");
// Method to handle the changes in the input field
const handleInputChange = (e) => {
setInput(e.target.value);
};
// Method to generate QR code
const generateQRCode = () => {
// toDataURL() from qrcode converts website link into QR code
QRCode.toDataURL(input, (err, input) => {
if (err) {
console.error(err);
return;
}
// Set the Qr code once it is generated
setQrCode(input);
});
};
return (
<div className="qr-generator">
<div className="input-container">
<input
type="text"
id="input"
placeholder="Eg: https://google.com/ "
value={input}
onChange={handleInputChange}
/>
<button className="submit" onClick={generateQRCode}>
Generate
</button>
</div>
{qrCode && (
<div className="display-container">
<img src={qrCode} alt="QR code" id="qr" />
<a className="download-btn" href={qrCode} download="qrcode.png">Download QR Code</a>
</div>
)}
</div>
);
}
export default QrGenerator;
With adding the logic to the component, you will now be able to see the entire working of the controls and display. The output will look like this
Congratulations 🎉!
You have successfully created your own QR code generator application.
In the next module, we will look into the steps to deploy the project using vercel.
See you in the next module!