1

I'm trying to use the react-barcodes library and it's really fantastic. The problem I'm having is using hooks (which must be declared at the top of the function, non-conditionally, etc.) and also iterate through an array to use different values for the bar code. I think this is a more general React and hooks issue than anything specific to react-barcodes. The example provided [here][1] works just great. However, here's what I'm trying to do:

import { useBarcode } from "react-barcodes";

const BarCodeTest = (props) => {
  var data = [
    {
      barCodeValue: "123",
    },
    { barCodeValue: "456" },
  ];

  // I want to change the "value" property here for each
  const { inputRef } = useBarcode({
    value: "initial value of some kind",
    options: {
      displayValue: true,
      height: 50,
    },
  });

// how can I set the value property as I iterate through data[]?  
return <>{data && data.map((item, index) => <svg ref={inputRef} />)}</>;
};

export default BarCodeTest;


  [1]: https://github.com/Bunlong/react-barcodes#-usage

1 Answer 1

1

you can actually break this into two components one is what you currently have and they other you can call it BarCodeItem and you can iterate over your data and send barcodeValue as a prop to BarCodeItem and then you can handle the hook easily like this below : this how you would go about things generally in react .

import React, { useRef } from "react";
import { useBarcode } from "react-barcodes";


const BarCodeItem = ({barcodeValue}) => {

  const { inputRef } = useBarcode({
    value: barcodeValue,
    options: {
      displayValue: true,
      height: 50,
    },
  });

  return <svg ref={inputRef} />;
};

const BarCodeTest = (props) => {
  var data = [
    {
      barCodeValue: "123",
    },
    { barCodeValue: "456" },
  ];

// how can I set the value property as I iterate through data[]?  
return <>{data && data.map((item, index) => <BarCodeItem key={index} barcodeValue={item.barCodeValue} />)}</>;
};


export default BarCodeTest;
Sign up to request clarification or add additional context in comments.

2 Comments

Gorgeous, thanks so much! I figured it was something relatively simple.
yeah very simple indeed

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.