Introduction: In this tutorial, we will explore how to build a QR Code Scanner application using React. We'll cover everything from setting up the project to executing it, along with code snippets and explanations. By the end, you'll have a fully functional QR Code Scanner app that you can use to scan and save QR codes.
Table of Contents:
Setting up the Project
Creating the Home Page
Implementing the QR Code Scanner
Saving Scanned QR Codes
Creating the About Page
Styling the Application
Conclusion
Setting up the Project: To get started, make sure you have Node.js and npm (Node Package Manager) installed on your machine. Then, follow these steps:
Step 1:
Open your terminal and navigate to the desired directory where you want to create your project.
Step 2:
Run the following command to create a new React project using Create React App:
create-react-app qr-code-scanner
Step 3:
Once the project is created, navigate into the project directory:
codecd qr-code-scanner
Step 4:
Install additional dependencies:
install react-router-dom react-qr-reader
Step 5:
Replace the default files in the src
folder with the necessary components and assets.
Creating the Home Page: The Home page will serve as the landing page of our application. Follow these steps to create it:
Step 1: Create a new file Home.jsx
inside the src
folder and import the necessary dependencies. Step 2: Define the Home
functional component and return the JSX markup for the home page layout. Step 3: Style the home page using CSS or inline styles. Step 4: Export the Home
component as the default export.
import React from 'react';
import { Link } from 'react-router-dom';
import './Home.css'; // Import the CSS file for styling
import leftImage from './images/left.png';
import rightImage from './images/right.png';
const Home = () => {
return (
<div className="home-container">
<h1 className="heading">QR Code Generator</h1>
<div className="image-container">
<div className="left-image-container">
<img src={leftImage} alt="Left Image" className="image left-image" />
</div>
<div className="button-container">
<Link to="/scan" className="button">Scan</Link>
<Link to="/saved" className="button">Saved</Link>
<Link to="/about" className="button">About</Link>
</div>
<div className="right-image-container">
<img src={rightImage} alt="Right Image" className="image right-image" />
</div>
</div>
</div>
);
};
export default Home;
Implementing the QR Code Scanner:
The QR Code Scanner functionality will allow users to scan QR codes using their device's camera. Follow these steps to implement it:
Step 1: Create a new file ScanPage.jsx
inside the src
folder and import the necessary dependencies. Step 2: Define the ScanPage
functional component and set up state variables and handlers for scanning and saving QR codes. Step 3: Implement the QR code scanning logic using the react-qr-reader
package. Step 4: Save the scanned QR codes to the state and display them on the page. Step 5: Style the Scan page using CSS or inline styles. Step 6: Export the ScanPage
component as the default export.
Code snippet for ScanPage.jsx
:
import React, { useState } from 'react';
import QRCode from 'qrcode.react';
import { useNavigate } from 'react-router-dom';
import './ScanPage.css';
const ScanPage = ({ savedLinks, setSavedLinks }) => {
const [link, setLink] = useState('');
const [generatedQR, setGeneratedQR] = useState('');
const navigate = useNavigate();
const handleLinkChange = (event) => {
setLink(event.target.value);
};
const handleGenerateQR = () => {
setGeneratedQR(link);
};
const handleDownloadQR = () => {
const canvas = document.getElementById('qrcode');
const dataURL = canvas.toDataURL('image/png');
const downloadLink = document.createElement('a');
downloadLink.href = dataURL;
downloadLink.download = 'qrcode.png';
downloadLink.click();
};
const handleSaveQR = () => {
// Save the generated QR code or its associated data
setSavedLinks((prevLinks) => [...prevLinks, generatedQR]);
// Redirect to the Saved component
navigate('/saved');
};
return (
<div className="scan-page-container">
<h2>Generate QR Code</h2>
<div className="input-container">
<input
type="text"
value={link}
onChange={handleLinkChange}
placeholder="Enter the link"
/>
<button onClick={handleGenerateQR}>Generate</button>
</div>
{generatedQR && (
<div className="qrcode-container">
<QRCode id="qrcode" value={generatedQR} size={200} />
<div>
<button onClick={handleDownloadQR}>Download</button>
<button onClick={handleSaveQR} style={{ marginLeft: '10px' }}>Save</button>
</div>
</div>
)}
</div>
);
};
export default ScanPage;
Saving Scanned QR Codes:
To save the scanned QR codes and view them later, we'll create a Saved page. Follow these steps:
Step 1: Create a new file Saved.jsx
inside the src
folder and import the necessary dependencies. Step 2: Define the Saved
functional component and pass the saved links as props. Step 3: Display the saved QR codes on the page and provide an option to delete them. Step 4: Style the Saved page using CSS or inline styles. Step 5: Export the Saved
component as the default export.
Code snippet for Saved.jsx
:
import React, { useState } from 'react';
import { saveAs } from 'file-saver';
import './Saved.css';
const Saved = ({ savedLinks, deleteLink }) => {
const handleDelete = (index) => {
deleteLink(index);
};
const handleDownload = async (link, index) => {
try {
const response = await fetch(
`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(link)}`
);
const blob = await response.blob();
saveAs(blob, `qrcode_${index}.png`);
} catch (error) {
console.error('Error occurred while handling download:', error);
}
};
const handleEnlargeQR = (index) => {
setEnlargedIndex(index);
};
const handleCloseEnlarged = () => {
setEnlargedIndex(null);
};
const [enlargedIndex, setEnlargedIndex] = useState(null);
return (
<div className="saved-page-container">
<h2>Saved Links</h2>
{savedLinks.map((link, index) => (
<div key={index} className="saved-link-container">
<div className="link-container">
<a href={link} className="saved-link" target="_blank" rel="noopener noreferrer">
{link}
</a>
<div className="qr-container">
<img
className={`qr-code ${enlargedIndex === index ? 'enlarged' : ''}`}
id={`qrcode_${index}`}
src={`https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(
link
)}`}
alt="QR Code"
onClick={() => handleEnlargeQR(index)}
/>
</div>
<div className="button-container">
<button className="download-button" onClick={() => handleDownload(link, index)}>
Download
</button>
<button className="delete-button" onClick={() => handleDelete(index)}>
Delete
</button>
</div>
</div>
</div>
))}
{enlargedIndex !== null && (
<div className="enlarged-overlay" onClick={handleCloseEnlarged}>
<img
className="enlarged-qr"
src={`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(
savedLinks[enlargedIndex]
)}`}
alt="Enlarged QR Code"
/>
</div>
)}
</div>
);
};
export default Saved;
Creating the About Page:
The About page will provide information about the project and the developer. Follow these steps to create it:
Step 1: Create a new file About.jsx
inside the src
folder and import the necessary dependencies. Step 2: Define the About
functional component and return the JSX markup for the about page layout. Step 3: Style the About page using CSS or inline styles. Step 4: Export the About
component as the default export.
Code snippet for About.jsx
:
import React from 'react';
import './About.css'; // Import the CSS file for styling
const About = () => {
return (
<div className="about-container">
<h2 className="about-heading">About</h2>
<p className="about-description">
A brief description of what this project does and who it's for. This project is created by Ananya De.
The project highlights my React skills. This is a QR code generator.
</p>
<div className="about-links">
<p>
To know more about the project click the Hashnode link below:
<br />
<a href="HASHNODE_LINK">Hashnode Article</a>
<a href="HASHNODE_LINK">
<img src="https://img.icons8.com/arcade/48/document.png" alt="Hashnode" className="about-icon" />
</a>
</p>
<p>
To view the code behind the project click below:
<br />
<a href="GITHUB_LINK">GitHub Repository</a>
<img width="30" height="30" src="https://img.icons8.com/arcade/64/code.png" alt="code"/>
</p>
</div>
<div className="about-footer">
<div className="about-icons">
<p>Know about me more:
<img src="https://img.icons8.com/arcade/64/for-you.png" alt="For You" className="about-icon" />
<br/>
<br/>
<a href="GITHUB_PROFILE_LINK">
<img src="https://img.icons8.com/clouds/100/github.png" alt="GitHub" />
</a>
<a href="LINKEDIN_PROFILE_LINK">
<img src="https://img.icons8.com/clouds/100/linkedin.png" alt="LinkedIn" />
</a>
</p>
</div>
<img
src="https://img.icons8.com/hands/100/experimental-gift-hands.png"
alt="Experimental Gift Hands"
className="about-image"
/>
</div>
</div>
);
};
export default About;
Styling the Application:
To style the application, create CSS files for each component (Home.css
, ScanPage.css
, Saved.css
, About.css
) and apply styles as per your design requirements.
Now modify the App.js to make it functional
import React, { useState } from 'react'; import { HashRouter as Router, Routes, Route } from 'react-router-dom'; import Home from './home'; import ScanPage from './scanpage'; import Saved from './saved'; import About from './about'; const App = () => { const [savedLinks, setSavedLinks] = useState([]); const deleteLink = (index) => { setSavedLinks((prevLinks) => prevLinks.filter((_, i) => i !== index)); }; return ( <Router> <header style={{ backgroundColor: "#FEB624" }}> {/* Header content */} </header> <Routes> <Route path="/" element={<Home />} /> <Route path="/scan" element={<ScanPage savedLinks={savedLinks} setSavedLinks={setSavedLinks} />} /> <Route path="/saved" element={<Saved savedLinks={savedLinks} deleteLink={deleteLink} />} /> <Route path="/about" element={<About />} /> {/* Other routes */} </Routes> {/* Rest of your content */} </Router> ); }; export default App;
Conclusion:
Congratulations! You have successfully built a QR Code Scanner application using React. We covered the setup, creating pages, implementing the QR code scanner, saving scanned codes, and creating the About page. Feel free to explore further and enhance the application based on your needs.
Remember to import the necessary dependencies, set up the routes in the App.jsx
file, and apply global styles or theme as per your project requirements.
I have taken the images from https://www.freepik.com/ and removed the background of those images from an online background remover.
That's it! You now have a fully functional QR Code Scanner application built with React. Happy scanning!
You can have a look at my code from below:-
Follow me for more!!