paint-brush
How to Build a QR Code Generator in Reactby@terieyenike
58,493 reads
58,493 reads

How to Build a QR Code Generator in React

by TeriJuly 1st, 2022
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

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. 

Company Mentioned

Mention Thumbnail
featured image - How to Build a QR Code Generator in React
Teri HackerNoon profile picture

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

Prerequisites

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
    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 state
  • The library,
    qrcode.react
    , is used to render the generated QR code 
  • Next, the use of the
    downloadQRCode
    function attached to the
    onSubmit
    method of the
    <form>
    element as this is triggered by the submit event
  • On the
    <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 typed
  • A variable
    qrcode
    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 use of props in the component
  • Finally, the
    <button>
    element is disabled until the user input receives data

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 (created using a QR Code generator) 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
    qrcode.react
    component produces the canvas element in the DOM which gives you the ability to create content dynamically
  • The canvas is appended to the
    toDataURL
    method with the specified type parameter set to the file formate,
    image/png
  • Next, the anchor,
    <a>
    element is created and the
    href
    is set to the image that downloads the QR code when the button is clicked
  • 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
    setUrl
    variable which clears the input for the generated QR code as the form is submitted

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