This article will teach us how to generate a QR code in the React application.
Prerequisites of React
- Familiarity with HTML and JavaScript.
- node.js installed
Create React Project
To create a React app, use the following command in the terminal.
npx create-react-app matui
Install Bootstrap
Now install Bootstrap by using the following command.
npm install bootstrap
Now, open the index.js file and add the import Bootstrap.
import 'bootstrap/dist/css/bootstrap.min.css';
Install the QR code library using the following command.
npm i qrcode
Now right-click on the src folder and create a new component named 'qrcodeDemo.js'
import React from 'react'
import QRCode from "qrcode";
import { useEffect, useRef, useState } from "react";
function QrcodeDemo() {
const [text, setText] = useState("");
const canvasRef = useRef();
useEffect(() => {
QRCode.toCanvas(
canvasRef.current,
text || " ",
(error) => error && console.error(error)
);
}, [text]);
return (
<div>
<div class="col-sm-12 btn btn-info"> How to Create QR Code in React Application</div>
<div class="col-sm-6">
<input class="form-control"
value={text}
onChange={(e) => setText(e.target.value)}
/>
</div>
<br />
<canvas ref={canvasRef} />
</div>
);
}
export default QrcodeDemo
Now, import the qrcodeDemo component in the src/App.js file
import './App.css';
import QrcodeDemo from './qrcodeDemo'
function App() {
return (
<div className="App">
<QrcodeDemo/>
</div>
);
}
export default App;
Now, run the project using the 'npm start' command and check the result.
Summary
This article provides a step-by-step guide on generating QR code in a React application.