DEV Community

Cover image for Creating Dynamic QR Codes Using React.js: A Step-by-Step Tutorial
The ERIN
The ERIN

Posted on • Updated on

Creating Dynamic QR Codes Using React.js: A Step-by-Step Tutorial

Gone are the days when relying solely on traditional business cards was enough to make a lasting impression. Understanding that using a business card for your business might be considered old-fashioned, as you may run out of them or the person you give them to might misplace them. But fear not; dynamic QR codes offer a modern and efficient solution.

Imagine having the ability to instantly update contact information, special offers, or website links associated with a QR code without the hassle of reprinting and redistributing physical materials. That's where the magic of dynamic QR codes comes into play.

This tutorial will start by exploring the basics of QR codes and then delve into the world of React.js, a popular JavaScript library for building interactive user interfaces. It will guide you through creating and integrating dynamic QR codes into your projects, allowing you to enhance user experiences and revolutionize how you share information.

 

Prerequisite

To follow through with this tutorial, you need the following:

  • A basic understanding of React.js and its syntax

  • npm installed on your computer. You can get it here if you don’t have npm installed on your computer.

     

Project Demo

You can find the hosted demo of this article here. You can also find the GitHub repository, which contains all the code for this article, here.

 

Setting up the React.js project environment

Using Create React App, create a React.js project by running the following command in your terminal:

npx create-react-app qrcode-app

Enter fullscreen mode Exit fullscreen mode

The preceding command creates a new react application with the name qrcode-app using the create-react-app tool.

Next, to preview the application in the browser, navigate to the project directory and run the development server, accessible at http://localhost:3000.

cd qrcode-app

npm start
Enter fullscreen mode Exit fullscreen mode

Finally, install the dependency library for creating the QR code generator. In your terminal, run the following command:

npm i react-qr-code html-to-image
Enter fullscreen mode Exit fullscreen mode

[react-qr-code](https://www.npmjs.com/package/react-qr-code) is a JavaScript library designed for use with React to generate QR codes quickly. At the same time, [html-to-image](https://www.npmjs.com/package/html-to-image) is a JavaScript library that lets you capture and convert HTML elements, such as a specific portion of a webpage or an entire HTML structure, into an image. It provides a simple and convenient way to take snapshots or screenshots of HTML content and save it as an image file, such as PNG or JPEG.

 

Designing the QR Code Component

Now that you have your development setup, the next step is designing and developing the QR code component. This component will contain the structure of the QR code and its enhancement for a better user experience.

  • Inside the src directory, create a folder called components and a file named QrCodeGenerator.jsx in the folder. In the QrCodeGenerator component, add the following code snippet.
function QrCodeGenerator() {
  const [url, setUrl] = useState("");
  const [qrIsVisible, setQrIsVisible] = useState(false);
  const handleQrCodeGenerator = () => {
    if (!url) {
      return;
    }
    setQrIsVisible(true);
  };
  return (
    <div className="qrcode__container">
      <h1>QR Code Generator</h1>
      <div className="qrcode__container--parent" ref={qrCodeRef}>
        <div className="qrcode__input">
          <input
            type="text"
            placeholder="Enter a URL"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
          />

          <button onClick={handleQrCodeGenerator}>Generate QR Code</button>
        </div>
        {qrIsVisible && (
          <div className="qrcode__download">
            <div className="qrcode__image">
              <QRCode value={url} size={300} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
export default QrCodeGenerator;
Enter fullscreen mode Exit fullscreen mode

 

The QrCodeGenerator component is a simple QR Code generator that allows users to enter a URL and generate a corresponding QR Code. The component uses the useState hook to manage the state of the URL input field (url) and the visibility of the generated QR Code (qrIsVisible).

When the user clicks the "Generate QR Code" button, the handleQrCodeGenerator function is called. It checks if a URL has been entered and sets the qrIsVisible state to true, displaying the generated QR Code.

The component renders a container with a heading, an input field for entering the URL, and a button to trigger the QR Code generation. If the QR Code is visible (qrIsVisible is true), it renders the QR Code image using the QRCode component from a QR Code library.

Overall, this component provides a straightforward and user-friendly way to generate QR Codes based on the entered URL.

 

Styling the QrCodeGenerator Component

In the index.css file located at the root of the src folder. Go ahead and add the following CSS code.

 

@import url('https://fonts.googleapis.com/css2?family=Mulish:wght@200;300;400;500;600&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Mulish', sans-serif;
}

.qrcode__container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}

.qrcode__container--parent {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.qrcode__input {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 30%;
  margin-top: 20px;
}


.qrcode__input input {
  width: 100%;
  padding: 10px;
  font-size: 12px;
  outline: none;
  resize: none;
  border-radius: 5px;
  border: 1px solid #ccc;
  margin-bottom: 15px;
}

.qrcode__input button, 
.qrcode__download button {
  display: inline-block;
  padding: 7px;
  cursor: pointer;
  color: #fff;
  background-color: rgb(96, 96, 246);
  border: none;
  border-radius: 5px;
  font-size: 12px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.qrcode__download {
  display: flex;
  align-items: center;
  flex-direction: column;
  margin-top: 20px;
}

.qrcode__download button {
  margin-top: 10px;
}
Enter fullscreen mode Exit fullscreen mode

 

Enhancing the QR Code Component: Downloading the QR Code.

The ability for users to download the generated QR code (made with a QR Code generator) makes it helpful in a wide range of applications. The possibilities range from printing the code to embedding it on a website.

In the QrCodeGenerator component, update the codebase to add the download functionality using the power of refs and the html-to-image library.

Add the following code snippet to your codebase.

 

import { useState, useRef } from "react";
// other previous imports
import * as htmlToImage from "html-to-image";

function QrCodeGenerator() {

   // useState variables and the handleQrCodeGenerator previously defined   will be here 

  const qrCodeRef = useRef(null);
  const downloadQRCode = () => {
    htmlToImage
      .toPng(qrCodeRef.current)
      .then(function (dataUrl) {
        const link = document.createElement("a");
        link.href = dataUrl;
        link.download = "qr-code.png";
        link.click();
      })
      .catch(function (error) {
        console.error("Error generating QR code:", error);
      });
  };
  return (
    <div className="qrcode__container">
     // previous defined jsx tags and elements will be here 
        {qrIsVisible && (
          <div className="qrcode__download">
            <div className="qrcode__image">
              <QRCode value={url} size={300} />
            </div>
            <button onClick={downloadQRCode}>Download QR Code</button>
          </div>
        )}
      </div>
    </div>
  );
}
export default QrCodeGenerator;

Enter fullscreen mode Exit fullscreen mode

 

The updated and final code snippet imports the html-to-image library, which provides a function to convert HTML elements into images. The code defines a reference using the useRefhook called qrCodeRef. This reference is used to access the QR code element in the [DOM](https://react.dev/learn/manipulating-the-dom-with-refs).

The downloadQRCode function is defined and triggered when the user clicks the "Download QR Code" button.

Inside the downloadQRCode function, the htmlToImage.toPngfunction is called with the qrCodeRef.current element as the argument. This function converts the QR code element to a PNG image.

If the conversion is successful, a link element is created and configured to download the generated PNG image. The dataUrl obtained from the conversion is set as the href of the link. The download attribute is set to qr-code.png, specifying the downloaded image's filename.

Finally, the link element is clicked programmatically, triggering the download of the QR code image. If an error occurs during the conversion or downloading process, it is logged into the console.

 

Importing the QrCodeGenerator Component into App.js

In your App.js file, you need to import the QrCodeGeneratorcomponent. Importing the QrCodeGenerator component in the App.js file lets you use and render the QrCodeGenerator component within the App component.

import QrCodeGenerator from "./components/QrCodeGenerator";


function App() {

  return (
    <>
      <QrCodeGenerator/>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

 

With each step followed in this article, your web application should look like this.

 

 

Alternative Methods of Generating QR Codes for Your Websites.

There are several easy ways to generate a QR code for a website. Here are some simple options:

  • Online QR Code Generator Websites: Many websites, like Beaconstac, QRFY, QR.io, and qrcodemonkey, offer free QR code generation services. These websites typically provide a user-friendly interface where you can enter the URL of your website and customize the QR code design. Once you're satisfied with the settings, the website will generate the QR code, which you can download and use as needed.

     

  • QR Code Generator Mobile Apps: You can use dedicated QR code generator apps on your smartphone or tablet. These apps often have a straightforward interface where you can instantly input your website URL and generate a QR code. You can then save the QR code image to your device and use it in your desired context.

     

  • Browser Extensions: Some web browsers, like Google Chrome, Safari, and Microsoft Edge, offer QR code generator extensions that allow you to generate QR codes directly within the browser. These extensions often add a QR code generation option to the browser's menu or toolbar, making creating a QR code for the current webpage or a specific URL convenient.

 

Conclusion

Congratulations on completing this comprehensive tutorial on creating dynamic QR codes using React.js! Throughout this journey, you have gained valuable skills to integrate QR code functionality into your web applications seamlessly.

By leveraging the react-qr-code library, you have simplified the process of generating QR codes and explored various concepts, including user input handling, state management, and event handling. With these tools, you can create interactive QR code generator components that enhance the user experience.

QR codes serve as a powerful bridge between the physical and digital worlds, enabling seamless sharing of URLs, contact information, and access to exclusive content. By incorporating QR codes into your web applications, you can elevate functionality and provide convenient solutions for event registration, contactless payments, and product information.

With this knowledge, you can embark on your projects and create exceptional web applications featuring dynamic QR codes.

Happy coding!

Top comments (0)