admin管理员组文章数量:1394228
I have 6 refs:
const element0 = useRef(null)
const element1 = useRef(null)
const element2 = useRef(null)
const element3 = useRef(null)
const element4 = useRef(null)
const element5 = useRef(null)
and i have a ponent which is being created in a loop: (ponent below is simplified)
{documents.map((offer,i)=>(
<div ref={element...}> ////here is the problem. idk how to properly name ref in order to create references to all refs at the top.
<img src="......"/>
</div>
)
)}
i tried to do it in many ways:
<div ref={`element${i}`}>
<div ref={element[i]}>
but it does not work ):
I have 6 refs:
const element0 = useRef(null)
const element1 = useRef(null)
const element2 = useRef(null)
const element3 = useRef(null)
const element4 = useRef(null)
const element5 = useRef(null)
and i have a ponent which is being created in a loop: (ponent below is simplified)
{documents.map((offer,i)=>(
<div ref={element...}> ////here is the problem. idk how to properly name ref in order to create references to all refs at the top.
<img src="......"/>
</div>
)
)}
i tried to do it in many ways:
<div ref={`element${i}`}>
<div ref={element[i]}>
but it does not work ):
Share Improve this question asked Aug 2, 2022 at 12:25 Jakub GodlewskiJakub Godlewski 431 silver badge4 bronze badges 1-
1
const elements = [useRef(null), useRef(null), ...]
— Use an array, not individual variables. – deceze ♦ Commented Aug 2, 2022 at 12:26
3 Answers
Reset to default 6you can store all elements in one ref
, as you can see the below code.
const elementRef = useRef([]);
{documents.map((offer,i)=>(
<div ref={ref => {
elementRef.current[i] = ref
}}>
<img src="......"/>
</div>
)
)
}
You probably want to use the package use-dynamic-refs
npm i use-dynamic-refs
then you want to import useDynamicRefs into your code like that:
import useDynamicRefs from 'use-dynamic-refs';
and inside your functional ponent:
const [getRef, setRef] = useDynamicRefs();
at this point, you can simply do the following:
documents.map((offer,i)=>(
// Use i or any other "id" that for you is easy to be retrieved later
<div ref={setRef(i)}>
<img src="......"/>
</div>
)
)}
and at last, retrieve the refs by using getRef:
const myRef = getRef("my-index")
For more information, this is the npm page of the package used: https://www.npmjs./package/use-dynamic-refs
You need to use array
of ref
s
const elementRefs = useRef([])
useEffect(() => {
elementRefs.current = elementRefs.current.slice(0, documents.length);
}, [documents]);
{documents.map((offer,i)=>(
<div
key={i}
ref={el => elementRefs.current[i] = el} >
<img src="......"/>
</div>
)
)}
本文标签: javascripthow to create dynamic ref names in a loop REACTjsStack Overflow
版权声明:本文标题:javascript - how to create dynamic ref names in a loop REACTjs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744604168a2615253.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论