How to Make QR-Code Generator in React

In this article, we are going to make a QR-code generator in React. A QR-Code is a barcode which is readable by a machine. Nowadays, we all use QR-Codes for Wi-Fi, online transactions, at malls, etc. it is simply used frequently and makes life easier.

Since QR-Code is that much useful, let’s make our own QR-Code. In today’s project, we will create a generator for QR-Code. We will have an input field to add a link or URL, this URL can be anything like https://reactjsguru.com, and a button to submit this URL and generate the code for the given URL. We will make it a working QR-Code, if you scan the QR-Code it will redirect you to that link as well. So let’s move on to the project without wasting time.

Pre-requisites to Make QR-Code Generator in React

  • Basic knowledge of ReactJS.
  • Basic knowledge of CSS.
  • Basic knowledge of React props and hooks.
  • Installation of qr-code module.

Adding The Required Modules

First, we need to import our required modules in the App.js file, Of course, we will add our React module but here we also need another module for the QR-code generator. For this, we need to install the qrcode module using the npm install qrcode command in the console. Because of this module, we can generate the QR code as a string, and we can add this string to our <img> tag to get our QR code as an image.

Here we have imported QR-Code from qrcode module, and also we have added our useState hook from our React module. We need this hook because once we generate the QR-Code, we need the URL and QR-Code, so they won’t get erased.

import QRCode from 'qrcode'
import { useState } from 'react'

Adding States

Now after, adding the modules, let’s move to the code, here we have added our main function name App. In which we are going to write our logic, simply, App is our component here. In this, we created two useState hooks, one for URL and the Other one for QR. setUrl and setQr are updated values, which will set the updated value to the url and qr. We have added current values for url and qr to '' (null string ) specified in the useState(''). If you want to learn more about useState hook, you can see here. And finally, we have exported this component, so that our index.js file can access content from this App.js component.

function App() {
	const [url, setUrl] = useState('')
	const [qr, setQr] = useState('')
}

export default App

Adding Return Value to App

Now after creating our states for QR and URL, we need to create the structure in which we will add input field, generate button, Qr-Code image, and download button. In this, we have created a div with class name app, and we have added one heading tag with QR Generator text.

Then we added an input field that has text type, a place-holder with an example of URL, and a value in which we have added useState of URL. This URL value will be empty because we have assigned empty to this URL when we have defined it. Also, we have added onChange a property, in which we have fetched the user input value using e.target.value, this will give the value added by the user. We have set this value in the setUrl hook, which will update the value of url.

Then after we have added a button, we have added an onClick event listener to perform some work when it gets clicked. In this listener, we have added a function that should be run if the button gets clicked. We will define this function later.

After that, we have added our image, in which we will add our generated QR-Code. We will generate the code in the GenerateQRCode function. Also, we have added an anchor tag in which have added the download property, with the image name. Here href will help to target the image to be downloaded.

return (
		<div className="app">
			<h1>QR Generator</h1>
			<input 
				type="text"
				placeholder="e.g. https://google.com"
				value={url}
				onChange={e => setUrl(e.target.value)} />
			<button onClick={GenerateQRCode}>Generate</button>
			{qr && <>
				<img src={qr} alt="qr-code"/>
				<a href={qr} download="qrcode.png">Download</a>
			</>}
      {
        console.log(qr)
      }
		</div>
	)
QR-Code Generator in React

Generating The Code

Now let’s move to our main and final part to generate our code, Here we need the function name GenerateQRCode which we have already added to the click event on the generate button. In this function, we will use QRCode.toDataURL() method, a method that will make the QR-Code for the given URL. Here, we will add the current value of the useState hook as our URL. In the React, return() will run first, so that url will have the user input value in it.

Now, we will add some style here, to get a certain amount of width and some color variations. Then we added an error message to show in the console if the url is wrong.

const GenerateQRCode = () => {
		QRCode.toDataURL(url, {
			width: 800,
			margin: 2,
			color: {
				dark: '#335383FF',
				light: '#EEEEEEFF'
			}
		}, (err, url) => {
			if (err) return console.error(err)

			console.log(url)
			setQr(url)
		})
	}
QR-Code Generator in React

Customization of The App

We have mainly focused on the React code, so we don’t get into the CSS part in deep. In the CSS part, we just have added some basic styles to the app, which purely depends on you to customize it. You can add the below CSS to your project if you don’t want to add much more things.

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: sans-serif;
}

body {
	text-align: center;
	background-color: #1b2034;
	color: #fff;
}

img {
	display: block;
	width: 480px;
	height: 480px;
	margin: 2rem auto;
}

.app {
	padding: 2rem;
}

h1 {
	font-size: 2rem;
	margin-bottom: 1rem;
}

input {
	appearance: none;
	outline: none;
	border: none;
	background: #EEE;
	width: 100%;
	max-width: 320px;
	padding: 0.5rem 1rem;
	border-radius: 0.5rem;
	margin-right: 1rem;
}

button, a {
	appearance: none;
	outline: none;
	border: none;
	background: none;
	cursor: pointer;

	color: #2bcb4b;
	font-size: 1.5rem;
	text-decoration: none;
}

Full Source Code to Make QR-Code Generator in React

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

App.js

import QRCode from 'qrcode'
import { useState } from 'react'

function App() {
	const [url, setUrl] = useState('')
	const [qr, setQr] = useState('')

	const GenerateQRCode = () => {
		QRCode.toDataURL(url, {
			width: 800,
			margin: 2,
			color: {
				dark: '#335383FF',
				light: '#EEEEEEFF'
			}
		}, (err, url) => {
			if (err) return console.error(err)

			console.log(url)
			setQr(url)
		})
	}

	return (
		<div className="app">
			<h1>QR Generator</h1>
			<input 
				type="text"
				placeholder="e.g. https://google.com"
				value={url}
				onChange={e => setUrl(e.target.value)} />
			<button onClick={GenerateQRCode}>Generate</button>
			{qr && <>
				<img src={qr} alt="qr-code"/>
				<a href={qr} download="qrcode.png">Download</a>
			</>}
      {
        console.log(qr)
      }
		</div>
	)
}

export default App

index.css

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: sans-serif;
}

body {
	text-align: center;
	background-color: #1b2034;
	color: #fff;
}

img {
	display: block;
	width: 480px;
	height: 480px;
	margin: 2rem auto;
}

.app {
	padding: 2rem;
}

h1 {
	font-size: 2rem;
	margin-bottom: 1rem;
}

input {
	appearance: none;
	outline: none;
	border: none;
	background: #EEE;
	width: 100%;
	max-width: 320px;
	padding: 0.5rem 1rem;
	border-radius: 0.5rem;
	margin-right: 1rem;
}

button, a {
	appearance: none;
	outline: none;
	border: none;
	background: none;
	cursor: pointer;

	color: #2bcb4b;
	font-size: 1.5rem;
	text-decoration: none;
}

Output

QR-Code Generator in React

Check out the video reference here:

You may also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

21 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents