visit
The idea behind creating a quick response (QR) code generator is to translate data from images to text. A QR code is simply the representation of image data as text, and it has a lot of useful applications from restaurant menus and concert tickets, to online calendar invites, payments, and the list goes on.
In this tutorial, you will learn how to create a QR code using the JavaScript library, React. The benefit of using React is that it makes building frontend applications a breeze as it provides developers ways to reuse components.
To follow through this tutorial, the following will be covered:
Prerequisites
To complete this tutorial, you need the following:
Getting Started
Before writing a line of code, open your terminal and run the following command:
npx create-react-app qrcode-generator
The command above scaffolds the files and installs a few packages needed to create the React app.
Next, navigate to the project directory and run the development server which is accessible on
//localhost:3000
using the command below to preview the app in the browser:cd qrcode-generator
npm start
Finally, let’s install the dependency library required for creating the QR code generator. Run the command:
npm install qrcode.react
qrcode.react
: A React component to generate QR codes for rendering to the DOM.Great work so far!
The creation of the QR code generator will begin with creating the files and components that will contain the structure of the QR code. Inside the src directory, create a folder called components and a file named QrCode.js in the folder.
Copy and paste the following code:
// src/components/QrCode.js
import { useState } from "react";
import { QRCodeCanvas } from "qrcode.react";
const QrCode = () => {
const [url, setUrl] = useState("");
const downloadQRCode = (e) => {
e.preventDefault();
setUrl("");
};
const qrCodeEncoder = (e) => {
setUrl(e.target.value);
};
const qrcode = (
<QRCodeCanvas
id="qrCode"
value={url}
size={300}
bgColor={"#00ff00"}
level={"H"}
/>
);
return (
<div className="qrcode__container">
<div>{qrcode}</div>
<div className="input__group">
<form onSubmit={downloadQRCode}>
<label>Enter URL</label>
<input
type="text"
value={url}
onChange={qrCodeEncoder}
placeholder="//gzht888.com"
/>
<button type="submit" disabled={!url}>
Download QR code
</button>
</form>
</div>
</div>
);
};
export default QrCode;
The code snippets above do the following:
useState
is used to declare the initial state of the variable, url which is set to an empty string, and the setState
function, setUrl
used to update the stateqrcode.react
, is used to render the generated QR code downloadQRCode
function attached to the onSubmit
method of the <form>
element as this is triggered by the submit event<input>
element, the onChange
event handler with the function ‘qrCodeEncoder’
takes in the users’ input, gets its value and changes the QR code with each new input typedqrcode
is created. It takes in the QRCodeCanvas
component and passes some available prompts that customize and make the QR code visible on the browser. Check out the documentation to learn more about the in the component<button>
element is disabled until the user input receives dataIn the
src
folder, create the stylesheet, styles.css
responsible for the visual appeal of the appCopy and paste the following code:
/* src/styles.css */
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--font-color: 230 35% 7%;
}
body {
color: hsl(var(--font-color));
}
img {
max-width: 100%;
display: block;
}
.section {
padding: 2em 0;
display: flex;
min-height: 100vh;
align-items: center;
}
.container {
margin-inline: auto;
max-width: 75rem;
width: 85%;
}
.input__group {
display: flex;
margin-top: 2em;
}
input {
width: 100%;
padding: 1em 0.75em;
border: 1px solid #444343;
border-radius: 3px;
margin-bottom: 2em;
margin-top: 0.75em;
}
button {
border: unset;
background: hsl(231, 77%, 90%);
padding: 1em 0.75em;
color: hsl(var(--font-color));
cursor: pointer;
text-transform: uppercase;
font-weight: bold;
}
@media screen and (min-width: 768px) {
.section {
padding: 0;
}
input {
margin: 0;
}
.qrcode__container {
display: flex;
align-items: center;
}
.input__group {
margin-left: 3em;
}
input {
margin-bottom: 2em;
margin-top: 0.75em;
font-size: 1rem;
}
}
Next, import the QrCode.js file and stylesheet in the entry point of the app, App.js:
// src/App.js
import QrCode from "./components/QrCode";
import "./styles.css";
export default function App() {
return (
<div className="section container">
<QrCode />
</div>
);
}
With the steps complete, the app should look like this:
The option for users to download the generated QR code (created using a ) makes it useful in a wide variety of use cases. From printing the code to embedding it on a website, the use cases are unlimited.
Back in the
components/QrCode.js
file, let’s update the codebase to use refs
to access the document object model (DOM) nodes.// src/components/QrCode.js
import { useState, useRef } from "react";
// other import
const QrCode = () => {
const [url, setUrl] = useState("");
const qrRef = useRef(); // include this: call the useRef function
...
const qrcode = (
<QRCodeCanvas
id="qrCode"
value={url}
size={300}
bgColor={"#00ff00"}
level={"H"}
/>
);
return (
<div className="qrcode__container">
<div ref={qrRef}>{qrcode}</div> {/* include this */}
{/* form input container */}
</div>
);
};
export default QrCode;
Now, let’s update the
downloadQRCode
function in the QrCode.js
file to be able to click the download QR code button and save the canvas as an image file.// src/components/QrCode.js
// imports
const QrCode = () => {
// state
// useRef
const downloadQRCode = (e) => {
e.preventDefault();
let canvas = qrRef.current.querySelector("canvas");
let image = canvas.toDataURL("image/png");
let anchor = document.createElement("a");
anchor.href = image;
anchor.download = `qr-code.png`;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
setUrl("");
};
...
return (
<div className="qrcode__container">
<div ref={qrRef}>{qrcode}</div>
{/* form input container */}
</div>
);
};
export default QrCode;
In the
downloadQRCode
function, the following takes place:qrcode.react
component produces the canvas element in the DOM which gives you the ability to create content dynamicallytoDataURL
method with the specified type parameter set to the file formate, image/png
<a>
element is created and the href
is set to the image that downloads the QR code when the button is clickedsetUrl
variable which clears the input for the generated QR code as the form is submittedThe complete code for the component QrCode.js:
import { useState, useRef } from "react";
import { QRCodeCanvas } from "qrcode.react";
const QrCode = () => {
const [url, setUrl] = useState("");
const qrRef = useRef();
const downloadQRCode = (e) => {
e.preventDefault();
let canvas = qrRef.current.querySelector("canvas");
let image = canvas.toDataURL("image/png");
let anchor = document.createElement("a");
anchor.href = image;
anchor.download = `qr-code.png`;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
setUrl("");
};
const qrCodeEncoder = (e) => {
setUrl(e.target.value);
};
const qrcode = (
<QRCodeCanvas
id="qrCode"
value={url}
size={300}
bgColor={"#00ff00"}
level={"H"}
/>
);
return (
<div className="qrcode__container">
<div ref={qrRef}>{qrcode}</div>
<div className="input__group">
<form onSubmit={downloadQRCode}>
<label>Enter URL</label>
<input
type="text"
value={url}
onChange={qrCodeEncoder}
placeholder="//gzht888.com"
/>
<button type="submit" disabled={!url}>
Download QR code
</button>
</form>
</div>
</div>
);
};
export default QrCode;
The final result of the app should look like this:
This tutorial described the process of creating a QR code generator and how it can be downloaded for later use.