QR Code generator using useState

III Amigoes
2 min readMay 17, 2024

create a simple QR code generator using ReactJS with the useState hook and the qrcode.react library:

import React, { useState } from ‘react’;

import QRCode from ‘qrcode.react’;

function QRCodeGenerator() {

const [text, setText] = useState(‘’);

const handleChange = (event) => {

setText(event.target.value);

};

return (

<div>

<h1>QR Code Generator</h1>

<input

type=”text”

value={text}

onChange={handleChange}

placeholder=”Enter text to generate QR code”

/>

{text && <QRCode value={text} />}

</div>

);

}

export default QRCodeGenerator;

In this example:

We import React, useState from react, and QRCode from qrcode.react.

We define a functional component QRCodeGenerator.

Inside the component, we initialize a state variable text using useState. This state will hold the text that the user inputs.

We define a handleChange function that updates the text state whenever the user types in the input field.

In the JSX, we render an input field where users can type the text they want to convert into a QR code.

We conditionally render the QRCode component with the value of text. The QR code will be displayed only if there is some text entered by the user.

Make sure you have installed the qrcode.react library using npm or yarn before using this code. You can install it by running:

npm install qrcode.react, yarn add qrcode.react

This code will generate a QR code based on the text entered by the user in real-time.

--

--