Bar Codes
Same recipe as QR codes, just swap the library for JsBarcode. Handy for product labels, tickets, and inventory management.
Add a barcode
import JsBarcode from 'jsbarcode';
import { svgToURL } from '@ydesign/react-editor/utils/svg';
import { generateObjectId } from '@ydesign/core';
function generateBarcodeSvg(text: string, options?: JsBarcode.BaseOptions) {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
JsBarcode(svg, text, {
format: 'CODE128',
displayValue: true,
fontSize: 14,
margin: 10,
...options,
});
return svg.outerHTML;
}
async function addBarcode(store: any, text: string) {
const svgStr = generateBarcodeSvg(text);
store.addElement({
id: generateObjectId(),
type: 'Image',
src: svgToURL(svgStr),
left: 100,
top: 100,
width: 400,
height: 120,
custom: {
barcodeText: text,
barcodeFormat: 'CODE128',
},
});
}
addBarcode(store, '6901234567890');
Edit after selection
import { observer } from 'mobx-react-lite';
import { Input, Select } from 'antd';
const BarcodeEditor = observer(({ store }) => {
const el = store.selectedElements[0];
if (!el?.custom?.barcodeText) return null;
const regenerate = (text: string, format: string) => {
const svgStr = generateBarcodeSvg(text, { format: format as any });
store.set(
{
src: svgToURL(svgStr),
custom: { barcodeText: text, barcodeFormat: format },
},
el,
);
};
return (
<div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
<Input
value={el.custom.barcodeText}
onChange={e => regenerate(e.target.value, el.custom.barcodeFormat)}
/>
<Select
value={el.custom.barcodeFormat}
onChange={fmt => regenerate(el.custom.barcodeText, fmt)}
options={[
{ value: 'CODE128', label: 'CODE128 (most common)' },
{ value: 'EAN13', label: 'EAN-13 (retail — CN/EU)' },
{ value: 'UPC', label: 'UPC (retail — North America)' },
{ value: 'CODE39', label: 'CODE39 (industrial)' },
]}
/>
</div>
);
});
Quick reference
| Format | Data | Use |
|---|---|---|
CODE128 | Full ASCII | Shipping, logistics |
EAN13 | 13-digit numeric | Chinese / European retail |
UPC | 12-digit numeric | North American retail |
CODE39 | Alphanumeric + some symbols | Industrial labels, auto parts |
Pick the wrong format and JsBarcode throws or produces an invalid code — confirm the correct one with your business team before rolling out.
Key points
- Input validation: wrap the generation in
try/catchand show the user a clear message on bad input - Real-scan testing: always test with a physical scanner or phone, don't trust visual inspection
- Hi-res export: SVG is lossless, so Cloud Render API with
multiplier: 4prints cleanly
See also
- 👉 QR codes demo — same pattern, different generator
- 👉 Custom Section
- 👉 Scenes · Export