1

I am building a dynamic image grid and trying to find the actual height of each image in pixels to adjust the layout accordingly.

My problem is when trying to access ref.current.clientHeight which is undefined. I tried following this post How can I use multiple refs for an array of elements with hooks? but cant access the height of the image

    const Grid = ({ arr }) => {
    const ref = useRef([])
    const arrLength = arr.length;

    const [elRefs, setElRefs] = useState([])

    useEffect(()=> {
        setElRefs(elRefs => (
            Array(arrLength).fill().map((_, i) => elRefs[i] || createRef())
          ));
        },[arrLength])

    return (
        <Container>
            {arr && arr.length !== 0 ? arr.map((o, i) => {

           // I want to access the clientHeight here to pass to the GridCard component as a prop

                return (
                    <GridCard
                        key={i}
                        data={o}
                        width={"280px"}
                        height={"auto"}
                        ref={elRefs[i]}
                    >
                    </GridCard>

                )
            }) : null}
        </Container>
    );
}
export default Grid;
plorp
  • 47
  • 1
  • 7

1 Answers1

0

Have a look at package react-use-measure.

Sample usage:

const [ref, bounds] = useMeasure({ polyfill: ResizeObserver });
return (
    <Grid
      container
      ref={ref}
      className={clsx(classes.root, bounds.width <= 300 ? classes.narrow : undefined)}
      ...
koral
  • 2,807
  • 3
  • 37
  • 65