Creating QR Codes in React Applications

QR codes are everywhere. It's a handy way to link people to where they need to go.

I recently put together a new event app (Eventson) and needed QR codes to add to users' tickets. The qrcode.react library is probably the easiest way to add them to your app.

First, install the package using npm or yarn:

npm install qrcode.react

And then here's simple example of generating a QR code:

import { QRCodeSVG } from 'qrcode.react';

function QRCodeComponent() {
  return (
    <QRCodeSVG 
      value="https://example.com"
      size={256}
    />
  );
}

Customization Options

You'll see a full list of the options over on the docs, but here are some of the things I think a lot of people will find helpful:

Size and Styling

  • size: Controls the dimensions of the QR code (default: 128)
  • bgColor: Background color
  • fgColor: Foreground color
<QRCodeSVG
  value="https://example.com/newsletter"
  size={300}
  bgColor="#ffffff"
  fgColor="#000000"
/>

Including Images

You can add a centered image to your QR code using the imageSettings prop:

<QRCodeSVG
  value="https://example.com"
  size={256}
  imageSettings={{
    src: "/logo.png",
    height: 40,
    width: 40,
    excavate: true
  }}
/>

On excavate, we use this to ensure clean edges around your image. It stops it from merging into the QR code making it harder to scan depending on your image.

Dynamic Content

Since it's a React library it's easy to make content dynamic using state. Here's an example of a QR code generator with dynamic content:

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

function DynamicQRCode() {
  const [text, setText] = useState('');

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text for QR code"
      />
      
      {text && (
        <QRCodeSVG
          value={text}
          size={256}
          level="M"
          includeMargin={true}
        />
      )}
    </div>
  );
}

Browser Support

The library provides both SVG (QRCodeSVG) and Canvas (QRCodeCanvas) components. Use SVG for better scaling and Canvas for broader browser compatibility.

ReactjsQr
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.