Home > Software design >  How to add refs to an array in React Native?
How to add refs to an array in React Native?

Time:06-20

I want to store a ref in each elements of my arrays. Can I insert it direcrly in my array (modifying it) ?

    const item = [
  {
    id: "1",
    name: "Text1",
  },
  {
    id: "2",
    name: "Text2",
  },
];

CodePudding user response:

Yes you can. You should use a callback to get multiple refs and store them in either a state or just a ref. Something like this

const Comp = (props) => {
 const refs = useRef([]);

 return <>
   {props.items.map(i => <div
     key={i}
     ref={el => refs[i] = el}
    >
    {i}
    </div>)
   }
 </>
}
  • Related