Skip to content

Commit 4d523a6

Browse files
committed
feat: allowable maxWidth prop for barcode
Adds optional prop - maxWidth of the barcode and determines if the barcode width exceeds the maxWidth; if the maxWidth is exceeded it then calculates the barcode block width based uponn the encoded data length and maxWidth.
1 parent 0f41e7b commit 4d523a6

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

index.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ export default class Barcode extends PureComponent {
2525
/* Set the background of the barcode. */
2626
background: PropTypes.string,
2727
/* Handle error for invalid barcode of selected format */
28-
onError: PropTypes.func
28+
onError: PropTypes.func,
29+
/* Maximum width of the barcode */
30+
maxWidth: PropTypes.number
2931
};
3032

3133
static defaultProps = {
@@ -37,7 +39,8 @@ export default class Barcode extends PureComponent {
3739
lineColor: '#000000',
3840
textColor: '#000000',
3941
background: '#ffffff',
40-
onError: undefined
42+
onError: undefined,
43+
maxWidth: undefined
4144
};
4245

4346
constructor(props) {
@@ -64,10 +67,19 @@ export default class Barcode extends PureComponent {
6467

6568
update() {
6669
const encoder = barcodes[this.props.format];
67-
const encoded = this.encode(this.props.value, encoder, this.props);
70+
let encoded = this.encode(this.props.value, encoder, this.props);
71+
let { width, maxWidth } = this.props;
72+
73+
if (maxWidth && encoded) {
74+
const length = encoded.data.length * width;
75+
if (length > maxWidth) {
76+
width = maxWidth / encoded.data.length;
77+
encoded = this.encode(this.props.value, encoder, {...this.props, width})
78+
}
79+
}
6880

6981
if (encoded) {
70-
this.state.bars = this.drawSvgBarCode(encoded, this.props);
82+
this.state.bars = this.drawSvgBarCode(encoded, {...this.props, width});
7183
this.state.barCodeWidth = encoded.data.length * this.props.width;
7284
}
7385
}

0 commit comments

Comments
 (0)