Louis Lecouturier
Louis Lecouturier

Reputation: 408

Get size of each element returned using map function in React

I want to do some operations with the size of some elements in my React application.

What I would usually do is using refs But the thing is that my elements are rendered in a map loop like so :

listings.map((listing, index) => <div key={index} className={styles.listing}>listing {index}</div>)

How can I retrieve the size of each elements rendered using this Array.map ?

(I need the size to do some computation to get an appropriate "max-height" value for each element).

Thanks for your help !

Upvotes: 0

Views: 1182

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

Can create a series of useRef and assign them to element

const refs = useRef(listings.map(React.createRef))

listings.map((listing, index) => <div key={index} className={styles.listing} ref={refs.current[index]}>listing {index}</div>)

Upvotes: 1

Related Questions