1

Is it possible to run html scripts in a specific React component only, instead of directly in index.html. The script loads a third party barcode scanner, which is only being used in one component, and therefore I want to avoid loading it for every component as this will slow the whole app down.

The npm module can be found here: https://www.npmjs.com/package/dynamsoft-javascript-barcode but there is no documentation on how to import it, only to include it like this:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/dbr.js" data-productKeys="LICENSE-KEY"></script> 
<script>
  let barcodeScanner = null;
        Dynamsoft.BarcodeScanner.createInstance({
            onFrameRead: results => {console.log(results);},
            onUnduplicatedRead: (txt, result) => {alert(txt);}
        }).then(scanner => {
            barcodeScanner = scanner;
            barcodeScanner.show();
        });
</script> 

2 Answers 2

1

Here is the React sample provided by Dynamsoft GitHub repository: https://github.com/dynamsoft-dbr/javascript-barcode/tree/master/example/web/react

You can check out Dynamsoft.js and HelloWorld.js to see how to import and use the module:

import Dynamsoft from "dynamsoft-javascript-barcode";
Dynamsoft.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/[email protected]/dist/";
// Please visit https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx to get a trial license
Dynamsoft.BarcodeReader.productKeys = "PRODUCT-KEYS";
// Dynamsoft.BarcodeReader._bUseFullFeature = true; // Control of loading min wasm or full wasm.
export default Dynamsoft;
import Dynamsoft from "../Dynamsoft";
import React from 'react';

class HelloWorld extends React.Component {
    ...
    let reader = this.reader = this.reader || await Dynamsoft.BarcodeReader.createInstance();
    ...
}

Note: This sample uses 7.3.0-v1. 7.2.2-v2 does not support this usage.

Sign up to request clarification or add additional context in comments.

Comments

1

I haven't tried this code but I have done some code like this.You can add script tag like this:

class YourComponent extends React.Component {
  loadScript() {
    let script = document.createElement("script");
    script.src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/dbr.js";
    script.setAttribute("data-productKeys","LICENSE-KEY");
    script.type = "text/javascript";
    document.head.append(script);
  }
  componentWillMount() {
    if(!YourComponent.bScriptLoaded){
      this.loadScript();  
      YourComponent.bScriptLoaded = true; 
    }
  }
}

This will add script tag in head tag and.And after that you can run your code in component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.