mateoc15
mateoc15

Reputation: 654

Using array mapping with hooks

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

Upvotes: 1

Views: 169

Answers (1)

سعيد
سعيد

Reputation: 1764

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;

Upvotes: 1

Related Questions