React Integration Example
Start a Cordova Project #
- Install Cordova: npm install -g cordova
- Create a New Cordova Project: cordova create my-cordova-app com.example.cordovaapp CordovaApp
- Navigate into the Cordova Project: cd my-cordova-ap
- Add Platforms: cordova platform add ios or cordova platform add android
- Open IDE and Start Coding: Open your chosen IDE or text editor and start building your app using web technologies.
- 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”
Using 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 './config/BarcodeScanner.js';
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 () => {
setScannedResult(null);
setIsScanning(true);
try {
const boundingRect = barkoderViewRef.current.getBoundingClientRect();
window.Barkoder.registerWithLicenseKey('ADD_YOUR_LICENSE_KEY_HERE');
await new Promise((resolve, reject) => {
window.Barkoder.initialize(
Math.round(boundingRect.width),
Math.round(boundingRect.height),
Math.round(boundingRect.x),
Math.round(boundingRect.y),
() => {
resolve();
},
(error) => {
reject('Initialization error: ' + error);
}
);
});
await setBarkoderSettings();
await setActiveBarcodeTypes();
window.Barkoder.startScanning(
(barkoderResult) => {
setScannedResult({
textualData: barkoderResult.textualData,
type: barkoderResult.barcodeTypeName,
resultImage: "data:image/jpeg;base64," + barkoderResult.resultImageAsBase64,
thumbnailImage: "data:image/jpeg;base64," + barkoderResult.resultThumbnailAsBase64,
});
window.Barkoder.stopScanning();
setIsScanning(false);
},
(error) => {
console.error('Scanning error:', error);
}
);
} catch (error) {
alert('Error: ' + error);
}
};
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">
<button className="actionButton" onClick={startScanning} disabled={isScanning}>Start Scanning</button>
<button className="actionButton" onClick={stopScanning} disabled={!isScanning}>Stop Scanning</button>
{scannedResult && (
<div className="resultContainer">
<p>Result:
<a href={scannedResult.textualData}>{scannedResult.textualData}</a>
</p>
<p>Type: {scannedResult.type}</p>
<img className="resultImage" src={scannedResult.thumbnailImage} alt="Scanned Thumbnail" />
</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 BarcodeScanner.js in plugins/barkoder-cordova-plugin/www/.
- Copy BarcodeScanner.js to the src directory of your React project, e.g., src/config/BarcodeScanner.js.
- 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