Home > Software design >  React Typescript: Use a react hook on each item in an array
React Typescript: Use a react hook on each item in an array

Time:12-08

I'm struggling on using a hook on each item on an array within my React Typescript project.

Without considering the limitations on using hooks, the code would be the following:

const forwardContractArray = useGetForwardArray()

interface ForwardResult {
        token: string;
        amount: number;
        expiryTime: number;
    }

const forwardResultArray: Array<ForwardResult> = []

for (let forwardAddress of forwardContractArray) {
  const { token, amount, expiryTime} = useForwardInfo(forwardAddress)
  forwardResultArray.push({token, amount, expiryTime})
}

Because of the limitations on running hooks in a for loop this is not possible to use a for loop for this.

Please could someone direct me on how to implement such a function within the scopes of React?

Thanks in advance.

CodePudding user response:

React is first and foremost a UI library - so, if you want to show something for each element of an array, then you can have a component per item and inside the component you can use a single hook

return (
  <>
    { forwardContractArray
        .map(item => <ItemDisplay key={item.token} item={item} />) }
  </>
)

and then e.g.

function ItemDisplay({ item } : { item: ForwardResult }) {
  const { token, amount, expiryTime} = useForwardInfo(item);
  return (
    <p>Whatever you want to show for this item</p>
  )
}
  • Related