How To Generate a QR Code in React JS

Udemezue John - Oct 7 - - Dev Community

Introduction.

Creating QR codes in a React.js application is an exciting way to add functionality to your project, especially with the increasing need for touchless interactions.

QR codes are a convenient tool, whether you're directing users to a specific URL, displaying encoded data, or enabling quick access to app features.

In this blog post, I'll walk you through how to generate QR codes directly in a React app.

Why QR Codes?

QR (Quick Response) codes are essentially a type of two-dimensional barcode. They can store a variety of data types, including URLs, text, contact details, and more. Their ability to quickly relay information when scanned by a mobile device makes them incredibly useful for digital interactions.

When building an application with React, you might want to include QR codes for a variety of purposes. Instead of relying on external platforms, you can generate these codes directly in your app.

Tools You’ll Need

To generate QR codes in React, you can utilize a library called qrcode.react.

It’s a simple yet powerful tool that helps you generate QR codes dynamically. Here’s how to get started.

How Do I Generate a QR Code in React JS?

QR codes have become a mainstay in today's digital world. From payments to event tickets, they’re everywhere. Whether you're building a web app that needs QR codes for product tracking, user identification, or even contactless menus, React.js can make the process efficient and straightforward. Let's dive into how you can generate a QR code within a React application.

Step 1: Set Up Your React App.

If you’re starting from scratch, you can create a new React project using Create React App. Run the following command in your terminal:

npx create-react-app qr-code-generator
cd qr-code-generator
npm start

Enter fullscreen mode Exit fullscreen mode

This will set up a basic React app and start the development server.

Step 2: Install qrcode.react.

To generate the QR codes, install the qrcode.react package, which provides a QR code component that integrates seamlessly into React.

npm install qrcode.react

Enter fullscreen mode Exit fullscreen mode

This library will handle the heavy lifting of generating the QR codes for you.

Step 3: Basic QR Code Generation.

Once the library is installed, you can start generating QR codes. Open your App.js file and import the QRCode component from qrcode.react:

import React from 'react';
import QRCode from 'qrcode.react';

function App() {
  return (
    <div className="App">
      <h1>QR Code Generator</h1>
      <QRCode value="https://www.example.com" />
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Here, I’m generating a simple QR code that encodes a URL (https://www.example.com).

When this QR code is scanned, it will open the URL in a browser. The value prop in the QRCode component specifies the content of the QR code.

Step 4: Dynamic QR Codes.

To make your app more interactive, you might want to generate QR codes based on user input.

For example, you can create a text input field and generate a QR code based on the value entered by the user.

Here’s an updated version of App.js:

import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <div className="App">
      <h1>Dynamic QR Code Generator</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Enter text or URL"
      />
      <QRCode value={inputValue} />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now, as users type into the input field, the QR code updates dynamically based on their input.

This is useful for generating custom QR codes for various purposes such as sharing user profiles, URLs, or any other kind of information.

Step 5: Customizing the QR Code.

The qrcode.react library also allows for customization. You can adjust the size, color, and other attributes of the QR code.

For example, here’s how you can set a custom size and change the foreground and background colors:

<QRCode
  value={inputValue}
  size={256} // Set the size of the QR code
  bgColor="#ffffff" // Background color
  fgColor="#000000" // Foreground color
/>

Enter fullscreen mode Exit fullscreen mode

With these options, you can tailor the appearance of the QR code to match your application's design or specific requirements.

Step 6: Saving the QR Code as an Image.

Sometimes, you may need to allow users to download the generated QR code as an image.

This can be done by using a ref to access the QR code component and leveraging the built-in canvas element to trigger a download. Here’s an example:

import React, { useState, useRef } from 'react';
import QRCode from 'qrcode.react';

function App() {
  const [inputValue, setInputValue] = useState('');
  const qrRef = useRef();

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const downloadQRCode = () => {
    const canvas = qrRef.current.querySelector('canvas');
    const pngUrl = canvas
      .toDataURL('image/png')
      .replace('image/png', 'image/octet-stream');
    let downloadLink = document.createElement('a');
    downloadLink.href = pngUrl;
    downloadLink.download = 'qr-code.png';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  };

  return (
    <div className="App">
      <h1>Downloadable QR Code Generator</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Enter text or URL"
      />
      <div ref={qrRef}>
        <QRCode value={inputValue} size={256} />
      </div>
      <button onClick={downloadQRCode}>Download QR Code</button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

In this example, I’m using a ref to access the canvas element inside the QR code component.

When the user clicks the "Download QR Code" button, it generates a PNG image from the canvas and triggers a download.

Conclusion.

Generating QR codes in a React.js application is simple and flexible, thanks to the qrcode.react library.

The ability to allow users to download QR codes as images further enhances the user experience.

By implementing this feature, you can enhance the functionality of your app and provide users with an intuitive and interactive way to share or save information.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player