SPFx – React Barcode.

Sathish Nadarajan
 
Solution Architect
August 24, 2021
 
Rate this article
 
Views
704

In one of the webpart, I must create the barcode based on the value generated. For that, after few analyses, found a react package. Hence sharing the information for easy access.

The package name is, React-Barcode.
Install using the below commands from your VS Code Terminal.

npm i react-barcode
https://www.npmjs.com/package/react-barcode

The usage is as below.

import * as React from 'react';
import styles from './Barcodesample.module.scss';
import { IBarcodesampleProps } from './IBarcodesampleProps';
import { escape } from '@microsoft/sp-lodash-subset';
import Barcode from 'react-barcode';

export default class Barcodesample extends React.Component<IBarcodesampleProps, {}> {
  public render(): React.ReactElement<IBarcodesampleProps> {
    return (
      <div className={ styles.barcodesample }>

<div id={`${this.state.MyDynamicValue}`}  >
<div>
         <Barcode value={"000000000321"}
                width={2}
                height={100}
                format={"CODE128"}
                displayValue={true}
                textAlign={"center"}
                background={"#fff"}
                lineColor="#000000"
                margin={0}
                fontSize={20}
              /> 
</div>
</div>
      </div>
    );
  }
}

The Output is as below.

The tag Barcode is rendered as div with svg format image.

To store this, we can use the below lines of code.

let itemNosvg = document.getElementById(`${this.state.MyDynamicValue }`).getElementsByTagName("svg")[0];
        let itemNoblob = new Blob([new XMLSerializer().serializeToString(itemNosvg)], { type: 'image/svg+xml' });
        await sp.web.getFolderByServerRelativeUrl(`${serverRelativeUrl}/ Images/Barcodes`).files.add(`${this.state.MyDynamicValue}.svg`, itemNoblob, true);

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment