blog-teaser

React Integration Example with Cordova

Introduction


In today’s fast-paced development world, developers want the flexibility to use their favorite web technologies to build mobile apps. React and Apache Cordova together make this possible, allowing developers to write a single codebase in React and deploy it on Android and iOS using Cordova.

In this guide, we’ll walk you through how to integrate React with Cordova to build a hybrid mobile application.

Why Use React with Cordova?

  • Write Once, Deploy Everywhere – Use React to build web-based UI and deploy it on mobile devices using Cordova.
  • Access Native Features – Cordova plugins provide access to native device features like camera, GPS, and file system.
  • Faster Development – No need to learn Java/Kotlin for Android or Swift for iOS.

Step-by-Step Guide to React + Cordova Integration - Start a Cordova Project  

  1. Install Cordova:  npm install -g cordova
  2. Create a New Cordova Project: cordova create my-cordova-app com.example.cordovaapp CordovaApp
  3. Navigate into the Cordova Project: cd my-cordova-ap
  4. Add Platforms:  cordova platform add ios or cordova platform add android
  5. Open IDE and Start Coding: Open your chosen IDE or text editor and start building your app using web technologies.
  6. Build and Run: Use Cordova commands to build and run your app on different platforms. cordova build ios or cordova build android

Installation 

Add barkoder-cordova Plugin


cordova plugin add barkoder-cordova

Install Manually 


cordova plugin add “/your-path/barkoder-cordova”

Use the plugin with React 

  • In your Cordova app folder, run the following command: 

npx create-react-app react_app

The installation process may take a few minutes. After it is done, you should see a folder that appears in your workspace with the name you gave to your app.

After the installation is completed, change to the directory where your app was installed with cd react_app and finally run npm start to see your app live on localhost.

  • Configure React Build Output for Cordova: 

Update the react_app project's build configuration to output to the www directory, which is used by Cordova for building mobile applications. Edit package.json in your React project (react_app) to set the build output directory:

"scripts": {
 "start": "react-scripts start",
 "build": "react-scripts build && cp -r build/* ../www",
 "test": "react-scripts test",
 "eject": "react-scripts eject"
}

 

If you are encountering issues with the cp command on Windows, you can use a different method to copy the build output from your React project to the www directory of your Cordova project.

Install cross-env for cross-platform environment settings:

npm install --save-dev cross-env

Update the scripts section in package.json to use a platform-independent method for copying files. You can use cpx for this purpose, which is a cross-platform cp command.

  • First, install cpx:
npm install --save-dev cpx
  • Then, update your package.json:
"scripts": {
 "start": "react-scripts start",
 "build": "react-scripts build && cpx "build/**/*" ../www",
 "test": "react-scripts test",
 "eject": "react-scripts eject"
}
  • Build React Application:
cd react_app
npm run build
  • Make sure cordova.js script is included in public/index.html :
<script src="cordova.js"></script>
  • Test and Run Your App:

Navigate back to the Cordova project root and build and run the app:

cd ..
cordova build android
cordova run android

Example with React 

  • Create a new component, e.g., BarcodeScanner.js, in your React project:
import React, { useRef, useState, useEffect } from 'react';
import { BarcodeType } from "../plugins/barkoder-cordova-plugin/www/BarkoderConfig.ts";

const BarcodeScanner = () => {
    const barkoderViewRef = useRef(null);
    const [scannedResult, setScannedResult] = useState(null);
    const [isScanning, setIsScanning] = useState(false);

    useEffect(() => {
        document.addEventListener('deviceready', () => {
            barkoderViewRef.current = document.getElementById('barkoderView');
        }, false);
    }, []);

    const setActiveBarcodeTypes = async () => {
        try {
            await window.Barkoder.setBarcodeTypeEnabled(BarcodeType.code128, true);
            await window.Barkoder.setBarcodeTypeEnabled(BarcodeType.ean13, true);
            // Here you can add other BarcodeTypes like code11, code25, code39 etc.
        } catch (error) {
            console.error('Error setting active barcode types:', error);
            throw error;
        }
    };

    const setBarkoderSettings = async () => {
        try {
            window.Barkoder.setRegionOfInterestVisible(true);
            window.Barkoder.setRegionOfInterest(5, 5, 90, 90);
            window.Barkoder.setCloseSessionOnResultEnabled(false);
            window.Barkoder.setImageResultEnabled(true);
            window.Barkoder.setBarcodeThumbnailOnResultEnabled(true);
            window.Barkoder.setBeepOnSuccessEnabled(true);
            window.Barkoder.setPinchToZoomEnabled(true);
            window.Barkoder.setZoomFactor(2.0);
        } catch (error) {
            console.error('Error setting Barkoder settings:', error);
            throw error;
        }
    };

const startScanning = async () => {
  try {
    const boundingRect = await barkoderViewRef.current.getBoundingClientRect();
    await initializeBarkoder(boundingRect);
    setIsScanning(true);
    setScannedResult(null);

    document.addEventListener(
      "deviceready",
      async () => {
        if (window.Barkoder) {
          await window.Barkoder.startScanning(handleScanResult, (error) => {
            console.error("Scanning error:", error);
            setIsScanning(false);
          });
        } else {
          console.error("BarkoderScanner plugin not available");
          setIsScanning(false);
        }
      },
      false
    );
  } catch (error) {
    alert("Error: " + error.message);
    setIsScanning(false);
  }
};

const handleScanResult = (barkoderResult) => {
  setIsScanning(false);

  const decoderResults = Array.isArray(barkoderResult?.decoderResults)
    ? barkoderResult.decoderResults
    : [barkoderResult?.decoderResults];

  const newScans = decoderResults.map((result) => {
    return {
      id: Math.floor(Math.random() * 1000000),
      textualData: JSON.stringify(result?.textualData),
      type: JSON.stringify(result?.barcodeTypeName),
      resultImage: `data:image/jpeg;base64,${barkoderResult?.resultImageAsBase64}`,
      thumbnailImage: `data:image/jpeg;base64,${barkoderResult?.resultThumbnailsAsBase64[0]}`,
    };
  });

  setScannedResult(newScans[0]);
 
};


    const stopScanning = () => {
        window.Barkoder.stopScanning(
            () => setIsScanning(false),
            (error) => console.error('Stop scanning error:', error)
        );
    };

    return (
        <div id="container">
        <div id="barkoderView" ref={barkoderViewRef}> </div>
          <div className="btnContainer">
                {!isScanning && ( <div className="actionButton" onClick={startScanning}>
                  <img width="40" alt="scan icon" src="/assets/scan-circle.svg" />
                </div>
                )}
              <div className="result_text_img">
                <span className="result_title">{scannedResult?.type}</span>
                {scannedResult?.thumbnailImage && <img className="resultImage" src={scannedResult?.thumbnailImage} alt="Scanned Thumbnail" />}
                <p>Result:
                  <a href={scannedResult?.textualData}>{scannedResult?.textualData}</a>
                </p>
              </div>
          </div>
      </div>
    );
};

export default BarcodeScanner;
  • To add other barcode types, add the following line in the setActiveBarcodeTypes function:

await window.Barkoder.setBarcodeTypeEnabled(BarcodeType.code, true);
  • Add CSS to style the component (e.g., in App.css or a new CSS file):
#container {
    margin-top: 30px;
    text-align: center;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
}

#container p {
    font-size: 16px;
    line-height: 22px;
    color: #8c8c8c;
    margin: 0;
}

#container a {
    text-decoration: none;
    color: #007bff;
    word-wrap: break-word;
}

#barkoderView {
    height: 400px;
}

.btnContainer {
    display: flex;
    flex-direction: column;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
}

.actionButton {
    width: 100%;
    height: 40px;
    font-size: 16px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.actionButton:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

.resultContainer {
    margin-top: 20px;
    width: 100%;
}

.resultImage {
    width: 100%;
    max-width: 200px;
    height: auto;
    margin-top: 10px;
    border-radius: 5px;
}
  • Use the BarcodeScanner component in your main App.js or other components:
import React from 'react';
import BarcodeScanner from './BarcodeScanner';

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

export default App;
  • Locate BarkoderConfig in barkoder-cordova-plugin/www/BarkoderConfig.ts.
  • Copy BarkoderConfig .ts to the src directory of your React project, e.g., src/plugins/barkoder-cordova-plugin/www/BarkoderConfig.ts .
  • Rebuild the React Application
npm run build
  • Test and Run Your App:

Navigate back to the Cordova project root and build and run the app:

cd ..
cordova build android
cordova run android

 

Conclusion

You can download the whole code from here: https://github.com/barKoderSDK/cordova-react-app/tree/master which should be enough to get you started. With these steps you will have a working project built on cordova utilizing the reactJS frameworks. Here are some images how the built app should look for you once you succesfully build it and run it. 

 

Scanneractive on a react with cordova sample
Active Scanning
QR result captured successfully
QR code captured
QR result screen
Result screen for single barcode
List of results
List of captured barcodes

 

 

 

 
For more information, you can always visit our Documentation.

Latest Barcode Scanner SDK Articles,
Tutorials, and News