I'm very new to React. I'm trying to convert a bit of javascript into React.
It is for a barcode and I'm trying to control the width of the barcode by counting the chars in the generated string. This code works well in JS, but only for one value.
var generatedBarcode = '1234567890' // create barcode chars
var charCount = (`${generatedBarcode.length}`); // count barcode chars
console.log(charCount)
if (charCount == 9){var barcodeWidth = 2.60;}
else if (charCount == 10){var barcodeWidth = 2.38;}
else if (charCount == 11){var barcodeWidth = 2.24;}
else if (charCount == 12){var barcodeWidth = 2.10;}
else if (charCount == 13){var barcodeWidth = 1.95;}
else if (charCount == 14){var barcodeWidth = 1.85;} // etc. I have worked out the widths
else {var barcodeWidth = 0.75;};
I'd very much like to turn this code into a function so that I can generate multiple barcodes on a page and for each (with a different character length) work out the appropriate width.
If you can point me in the right direction, I'd be very grateful. I'm desperately trying to get my head around React!
Thanks very much!
Add your widths to array, and just call the function that returns your width. If your barcode starts with length of 9, just change [barcode.length] to [barcode.length - 9]
const barcodeWidths = [2.6, 2.38, 2.24, 2.1, 1.95, 1.85, ...etc.]
const getBarcodeWidth = (barcode) => {
return barcodeWidths[barcode.length]
}