DEV Community

Cover image for ReactJs QR Code Generator
Gayathri R
Gayathri R

Posted on • Edited on

ReactJs QR Code Generator

QR (Quick Response) codes are capable of storing lots of data, and users can easily access the information by scanning the QR code. In this blog, I'm going to explain to you how to create a QR Code Generator App using ReactJs.

Here's a preview:

Image description

Let's get started...

Create a new React Js project.

$ npx create-react-app qr-code-generator 
$ cd qr-code-generator
$ npm start
Enter fullscreen mode Exit fullscreen mode

Open the application into a VSCode editor. In that, expand the 'src' folder. Inside that you can see two files that is, 'App.css' and 'App.js'. Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called β€˜create-qr-code’ to fetch the required QR code image.

Now write down the following code in the App.js file.

import { useEffect, useState } from 'react';
import {useRef} from 'react';
import './App.css';

function App() {

  const inputRef = useRef(null);
  const [qrUrl, setWord] = useState("");
  const [qrImg, setQrCode] = useState("");
  const [active, setQrCodeStatus] = useState("");

  useEffect(() => {
    setQrCode
  (`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrUrl}`);
  },);

  function generateQR() {
    let qrValue = inputRef.current.value.trim();
    if(!qrValue) return;
    setWord(qrValue);
    setQrCodeStatus("active");
  }

  const inputChange = event => {
    if(event.target.value === '') setQrCodeStatus('inActive');
  };

  return (
    <div className={ `wrapper ${active} === 'active' ? "wrapper active" : "wrapper"` }>
      <header>
        <h1>QR Code Generator</h1>
        <p>Paste a url or enter text to create QR code</p>
      </header>
      <div class="form">
        <input ref={inputRef} onChange={inputChange} type="text" id="qr_code" name="qr_code" spellcheck="false" placeholder="Enter text or url" />
        <button onClick={generateQR}>Generate QR Code</button>
      </div>
      <div class="qr-code">
        <img src={qrImg} alt="qr-code" />
      </div>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now, let’s edit the file named App.css to design our app.

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  align-items: center;
  background: #3498DB;
  justify-content: center;
}
.wrapper{
  height: 265px;
  max-width: 410px;
  background: #fff;
  border-radius: 7px;
  padding: 20px 25px 0;
  transition: height 0.2s ease;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.wrapper.active{
  height: 530px;
}
header h1{
  font-size: 21px;
  font-weight: 500;
}
header p{
  margin-top: 5px;
  color: #575757;
  font-size: 16px;
}
.wrapper .form{
  margin: 20px 0 25px;
}
.form :where(input, button){
  width: 100%;
  height: 55px;
  border: none;
  outline: none;
  border-radius: 5px;
  transition: 0.1s ease;
}
.form input{
  font-size: 18px;
  padding: 0 17px;
  border: 1px solid #999;
}
.form input:focus{
  box-shadow: 0 3px 6px rgba(0,0,0,0.13);
}
.form input::placeholder{
  color: #999;
}
.form button{
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  font-size: 17px;
  background: #3498DB;
}
.qr-code{
  opacity: 0;
  display: flex;
  padding: 33px 0;
  border-radius: 5px;
  align-items: center;
  pointer-events: none;
  justify-content: center;
  border: 1px solid #ccc;
}
.wrapper.active .qr-code{
  opacity: 1;
  pointer-events: auto;
  transition: opacity 0.5s 0.05s ease;
}
.qr-code img{
  width: 170px;
}

@media (max-width: 430px){
  .wrapper{
    height: 255px;
    padding: 16px 20px;
  }
  .wrapper.active{
    height: 510px;
  }
  header p{
    color: #696969;
  }
  .form :where(input, button){
    height: 52px;
  }
  .qr-code img{
    width: 160px;
  }  
}
Enter fullscreen mode Exit fullscreen mode

Step to Run Application: Run the application using the following command from the root directory of the project:

$ npm start
Enter fullscreen mode Exit fullscreen mode

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Image description

Don’t forget to star the repo on GitHub. Stars keep me motivated and are highly appreciated.

Code reviews welcome. Let me know if I can do something better.

Top comments (3)

Collapse
 
brense profile image
Rense Bakker

Why not use this npm package? npmjs.com/package/react-qr-code

Also you really dont want to have useEffects without a dependency array... It will execute the useEffect code on every render which is never what you want.

This is probably what you want:

useEffect(() => {
  setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrUrl}`)
}, [qrUrl])
Enter fullscreen mode Exit fullscreen mode

Although in your example I wouldnt use a useEffect hook at all, you can keep it all in the generateQR function:

const generateQR = useCallback(() => {
  let qrValue = inputRef.current.value.trim()
  if(!qrValue) return
  setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`)
  setQrCodeStatus("active")
}, []);
Enter fullscreen mode Exit fullscreen mode

Or even make it an actual form submit, so you dont have to use refs:

function App() {
  const [qrCode, setQrCode] = useState("");
  const [status, setQrCodeStatus] = useState("");

  const generateQR = useCallback((formEvent) => {
    formEvent.preventDefault()
    const qrValue = formEvent.target.elements['qr_code'].value.trim()
    if(!qrValue) return
    setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`)
    setQrCodeStatus("active")
  }, []);

  const inputChange = useCallback(event => {
    if(event.target.value === '') setQrCodeStatus('inActive');
  }, []);

  return (
    <div className={ `wrapper ${active} === 'active' ? "wrapper active" : "wrapper"` }>
      <header>
        <h1>QR Code Generator</h1>
        <p>Paste a url or enter text to create QR code</p>
      </header>
      <form class="form" onSubmit={generateQR}>
        <input onChange={inputChange} type="text" id="qr_code" name="qr_code" spellcheck="false" placeholder="Enter text or url" />
        <button type="submit">Generate QR Code</button>
      </form>
      <div class="qr-code">
        <img src={qrImg} alt="qr-code" />
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gayathri_r profile image
Gayathri R

Thanks Rense Bakker! Your feedback is really useful for my react learning...

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

A better title for this would be "How to change the URL of an image using React" - since that's all you are doing.