How to create barcodes in ReactJS

We can make a barcode in ReactJS with PHP or any other Server-side language such as NodeJS, Java, or ASP.Net. How to create barcodes in ReactJS

I have used PHP for database communication. Because I will save all the data into the database.How to Generate Barcode with React JS

You can use custom number for barcode then You will not to have used PHP or any server side language.

You can see all the details about barcode : https://github.com/lindell/JsBarcode/wiki/Options

the react-barcode component is a lightweight and high-performance component that displays industry-standard 1D and 2D barcodes for React app. Generated barcodes are optimized for printing and on-screen scanning. It is designed for ease of use and does not require fonts.

First install barcode for your project . react-barcode is available on npm. It can be installed with the following command:

npm install --save @createnextapp/react-barcode

react-barcode is available on yarn as well. It can be installed with the following command:

yarn add @createnextapp/react-barcode

Now We will start our coding pare here. But Install bootstrap for responsiveness of project .

Download Source Code : React JS Bar Code Porject

Make one file isnide src of react folder ( src/Barcode.js)

Barcode.js

import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState, useEffect ,useParams} from "react";
import { useBarcode } from '@createnextapp/react-barcode';


function Barcode()

{
    const [barcod,setBarcod] = useState({
      productName:'',
      productNumber:''
    });

    const [getbarcode,setGetbarcode] = useState([]);
  
    const { productName, productNumber} = barcod; // Array Destructutring

  
   // Handling Input values here 

    const onInputChange = e => {
      setBarcod({ ...barcod, [e.target.name]: e.target.value });
    };
 
   // Code for fetching Barcode Number from database  on window load
    const  loadBrcode =()=>
    {
      var response = fetch('http://localhost/react_projects/react_barcod/load_barcode.php')
      .then(function(response){
           return response.json();
        })
      .then(function(myJson) 
        {
        setGetbarcode(myJson);
        });
    }

    useEffect(() => {
      loadBrcode();
    }, []);

      const { inputRef } = useBarcode({
        value:getbarcode.ProductNumber, //Product Number from database 
        options: {
          background: '#ffffff',
          fontSize: 20,
          margin: 30,
          fontOptions: "bold",
          width: 1,
          height:70
        }
      });
    
    // Code for Inserting barcode into database
    const submitResult = (e) =>
    {
        var proName = barcod.productName;
        var proNum = barcod.productNumber;
        let sendReqData = barcod;
        var response = fetch('http://localhost/react_projects/react_barcod/generate_barcode.php',{
          method:"POST",
          headers: {
           "Content-Type": "application/json",
          },
          body: JSON.stringify({ barCodeProductName:proName, barCodeProNum:proNum }), // This will send to php 
          }).then(function(response){
           return response.json();
          })
          .then(function(myJson) 
          {
            loadBrcode();
          });
    }      
  return(
  
    <div class="container">
      <h4 class="mt-3 text-success mb-4">Generate Barcode using ReactJS</h4>
      <div class="row">  
        <div class="col-sm-4" style={{border:"1px solid rgb(206 200 200)"}}>
      
        <h4 style={{color:"green"}} id="success"></h4>
        <h5 class="text-center  ml-4 mb-5 mt-4">Generate Barcode</h5>
          <div class="form-group">
           <input type="text" class="form-control  mb-4" value={productName} name="productName" onChange={e => onInputChange(e)}   placeholder="Enter Product Name" required=""/>
         </div>

         <div class="form-group">
          <input type="text" class="form-control  mb-4"  value={productNumber}  name="productNumber" onChange={e => onInputChange(e)}  placeholder="Enter Barcode Number" required=""/>
         </div>

        <button type="submit" class="btn btn-primary" onClick={submitResult} name="submit">Generate Barcode</button>  
      </div>    
      <div class="col-sm-8" style={{border:"1px solid rgb(206 200 200)"}}>
      <h5 class="text-center  ml-4 mb-5 mt-4">Barcodes</h5>
         <table class="table table-hover mb-5">
         <thead>
          <tr>
            <th>Id</th>
            <th>Product Name</th>
            <th>Barcode Number</th>
          </tr>
        </thead>
        <tbody id="output">
           <tr>
             <td>1</td>
             <td><h5>{getbarcode.ProductName}</h5></td>
             <td><svg ref={inputRef}/></td>
           </tr>    
        </tbody>
        </table>
    
        </div>
      </div>
    </div>    
 

  );
}

export default Barcode;

Now we will call this Barcode.js file inside our App.js file to display on browser.

App.js

import Barcode  from './Barcode';
import './App.css';

function App() {
  return (
    <div className="App">
      <Barcode />
    </div>
  );
}

export default App;

Our React Part is completed now We will look for PHP Code .

Database Table name is barcode and Column Name : id, product_name, product_number

generate_barcode.php

<?php

header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

 $conn = mysqli_connect('localhost','root','','barcode_react');

 $data = json_decode(file_get_contents("php://input"));

 $barcode_name =  $data->barCodeProductName;
 $barcode_num =  $data->barCodeProNum;

//  echo $barcode_name;
//  echo $barcode_num;
//  exit;

 $sql = "INSERT into barcode(product_name,product_num)VALUES('$barcode_name','$barcode_num')";

$query1 = mysqli_query($conn,$sql);

$select = "SELECT * FROM barcode";

$query = mysqli_query($conn,$select);

$output = []; //OR  $output = array(); 
  
   while($row=mysqli_fetch_assoc($query))
    {
        $output[] = array(  
          "ProductName" => $row['product_name'],    
          "ProductNumber" => $row['product_num']   
        ); 
    }

    echo json_encode($output);
    ?>

Now We make another file for loading data from database load_barcode.php

<?php

header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

 $conn = mysqli_connect('localhost','root','','barcode_react');

 $data = json_decode(file_get_contents("php://input"));

//  echo $barcode_name;
//  echo $barcode_num;
//  exit;

 
 $select = "SELECT * FROM barcode";
 
 $query = mysqli_query($conn,$select);

  //$output = []; //OR  $output = array(); 
  
   while($row=mysqli_fetch_assoc($query))
    {
        $output = array(  
          "ProductName" => $row['product_name'],    
          "ProductNumber" => $row['product_num']   
        ); 
    }

    echo json_encode($output);
    ?>

Everything is done now run this project in browser http://localhost:3000/

Download Source Code : React JS Bar Code Porject

Read our more tutorials

Dependent Dropdown in ReactJS

CRUD Operation in REACT JS

Responsive Website in REACT JS

Leave a Reply

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