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.
Teri Eyenike
I am a frontend developer with a particular interest in making things simple and usable.
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
- Getting started
- Creating a QR code generator
- Styling the QR code app
- Downloading the generated QR code
- Conclusion
- Resources
Demo
The demo for this project is in this
. Fork it and run the codePrerequisites
To complete this tutorial, you need the following:
- Basic understanding of React.js
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
http://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.
Creating a QR Code Generator
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="https://hackernoon.com"
/>
<button type="submit" disabled={!url}>
Download QR code
</button>
</form>
</div>
</div>
);
};
export default QrCode;
The code snippets above do the following:
- Import
is used to declare the initial state of the variable, url which is set to an empty string, and theuseState
function,setState
used to update the statesetUrl
- The library,
, is used to render the generated QR codeqrcode.react
- Next, the use of the
function attached to thedownloadQRCode
method of theonSubmit
element as this is triggered by the submit event<form>
- On the
element, the<input>
event handler with the functiononChange
takes in the users’ input, gets its value and changes the QR code with each new input typed‘qrCodeEncoder’
- A variable
is created. It takes in theqrcode
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 use of props in the componentQRCodeCanvas
- Finally, the
element is disabled until the user input receives data<button>
Styling the QR Code App
In the
src
folder, create the stylesheet,
styles.css
responsible for the visual appeal of the app
Copy 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:
Downloading the Generated QR Code
The option for users to download the generated QR code 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:
- It references the current value of the ref object with the .current property to know when the node changes
- The
component produces the canvas element in the DOM which gives you the ability to create content dynamicallyqrcode.react
- The canvas is appended to the
method with the specified type parameter set to the file formate,toDataURL
image/png
- Next, the anchor,
element is created and the<a>
is set to the image that downloads the QR code when the button is clickedhref
- The anchor element is appended to the document body and once the QR code is downloaded, it is removed
- Finally, the state url is updated with the
variable which clears the input for the generated QR code as the form is submittedsetUrl
The 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="https://hackernoon.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:
Conclusion
This tutorial described the process of creating a QR code generator and how it can be downloaded for later use.
Resources
L O A D I N G
. . . comments & more!
You may be interested in:
>> Is a Chromebook worth replacing a Windows laptop?
>> Find out in detail the outstanding features of Google Pixel 4a
>> Top 7 best earbuds you should not miss
Related Posts:
>> Recognizing 12 Basic Body Shapes To Choose Better Clothes
>>Ranking the 10 most used smart technology devices
>> Top 5+ Best E-readers: Compact & Convenient Pen
0 Comments:
Post a Comment