Introduction

In this article, I'm going to show how to create custom React components for generating a QR code based on the input provided in our React application.

Requirement

QR Code Generator Component in React

To create a QR code generator in React, start by setting up a React app using npx create-react-app qr-code-generator. Install the QR code package using npm i qrcode-generator. Create a QRCodeGenerator component using useState to handle input and QR code state. The QR code is generated from user input via the react-qr-code library. The handleGenerateQrCode function sets the QR code value based on the input. Integrate this component in App.js and run the app to see the QR code generator in action.

Please follow the given steps below.

Step 1. We need to create a new React app using the below command.

npx create-react-app qr-code-generator

Then, open the folder in the VS Code and open the command prompt to install the React QR Code generator package.

npm i qrcode-generator

Step 2. Create a new folder named components and then a new file named QRCodeGenerator.js and add the following code.

import { useState } from "react";
import QRCode from "react-qr-code";

export default function QRCodeGenerator() {
  const [qrCode, setQrCode] = useState("");
  const [input, setInput] = useState("");

  function handleGenerateQrCode() {
    setQrCode(input);
    setInput('')
  }

  return (
    <div>
      <h1>QR Code Generator</h1>
      <div>
        <input
          onChange={(event) => setInput(event.target.value)}
          type="text"
          name="qr-code"
          value={input}
          placeholder="Enter your value here"
        />
        <button
          disabled={input && input.trim() !== "" ? false : true}
          onClick={handleGenerateQrCode}
        >
          Generate QR Code
        </button>
      </div>
      <div>
        <QRCode id="qr-code-value" value={qrCode} size={400} bgColor="#fff" />
      </div>
    </div>
  );
}

Now, we need to use the QR Code generator Component in the App.js file by removing the default and using the below code.

import QRCodeGenerator from './QRCodeGenerator';
import './App.css';

function App() {
  return (
    <div className="App">
    <QRCodeGenerator />
    </div>
  );
}

export default App;

Then, you can run your application, and we can see the QR Code Generator locally in our React app.

QR Generator

This is the explanation of the code that we used on the QR Code Generator component.