Creating Dynamic QR Codes Using React.js: A Step-by-Step Tutorial
Tags: beginners, react, tutorial, javascript
Published: 2023-07-06 17:35:43

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](https://react.dev/), 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.
<p>&nbsp;</p>

## 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](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) if you don’t have npm installed on your computer.
<p>&nbsp;</p>


## Project Demo

You can find the hosted demo of this article [here](https://qrcode-web-app.netlify.app/). You can also find the GitHub repository, which contains all the code for this article, [here](https://github.com/OfficialJhimmy/qr-code-generator-app).  

<p>&nbsp;</p>

## Setting up the React.js project environment

Using [Create React App](https://react.dev/), create a React.js project by running the following command in your terminal:

```
npx create-react-app qrcode-app

```
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
```


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
```


`[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.

<p>&nbsp;</p>

## 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.


```jsx
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;
```


<p>&nbsp;</p>


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.
<p>&nbsp;</p>

## 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.
<p>&nbsp;</p>

```css
@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;
}
```

<p>&nbsp;</p>



## 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.

<p>&nbsp;</p>

```jsx
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;

```


<p>&nbsp;</p>

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 `useRef `hook 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.toPng `function 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.


<p>&nbsp;</p>


## Importing the QrCodeGenerator Component into `App.js`

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

```jsx
import QrCodeGenerator from "./components/QrCodeGenerator";


function App() {
  
  return (
    <>
      <QrCodeGenerator/>
    </>
  );
}

export default App;
```


<p>&nbsp;</p>


With each step followed in this article, your web application should look like this. 
<p>&nbsp;</p>


<img width="900" height="474"src=https://media.giphy.com/media/6rJahsrYwrKUKTjhJD/giphy.gif>


<p>&nbsp;</p>

## 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](https://www.beaconstac.com/qr-code-generator?utm_source=Medium&utm_medium=UXCollective), [QRFY](https://qrfy.com/en), [QR.io](https://qr.io/), and [qrcodemonkey](https://www.qrcode-monkey.com/), 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.
<p>&nbsp;</p>

- **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.
<p>&nbsp;</p>

- **Browser Extensions**: Some web browsers, like [Google Chrome](https://www.google.com/chrome/), [Safari](https://support.apple.com/downloads/safari), and [Microsoft Edge](https://www.microsoft.com/en-us/edge/download?form=MA13FJ), 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.

<p>&nbsp;</p>

## 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!