개발 공부/React
map으로 순회하는 component마다 ref 를 달 때
차정
2023. 1. 10. 16:00
순회하는 element에 모두 ref를 달지 않고 상위 element에만 ref를 달아준 뒤에
상위 ref에서 Array.from(상위element.ref).map 을 사용해도 되지만-
map으로 순회하는 component마다 ref를 달고 싶다면 ??
https://stackoverflow.com/questions/63059962/reactjs-map-with-a-ref-to-each-component
ReactJS .map with a ref to each component
Working on making it so when a user goes back a page in my react app they will be scrolled to the position on the page they were previously at. Specifically, to the item on a list that they had cli...
stackoverflow.com
1. ref를 사용할 상위 컴포넌트에서 ref 객체 선언
App.jsx
const allRefs = {};
2. ref 사용하는 컴포넌트에 allRefs 전달해 주고
Gallery.jsx
{gallerySideContentData.map((data, i) => (
<GalleryContent
key={i}
odd={i % 2}
data={data}
allRefs={allRefs}
/>
))}
3. 사용하는 컴포넌트 안에서 참조하는 dom에 대한 정보를 객체 (allRefs)에 넣어준다.
GalleryCotent.jsx
const GalleryContent = ({ odd, data, allRefs }) => {
console.log(data);
return (
<article className="gallery" ref={(ref) => (allRefs[data.title] = ref)}>
/* 중략 */
/* data의 구조
data = [{title: "A", desc:"aaaa"}, {title: "B", desc:"bbbb"}, {title: "C", desc:"cccc"} ]
*/