I want to get Height of an image in a react functional component using react hooks.
I have used below code:
import React, { useRef, useEffect } from 'react' const DepthChartContent = props => { const ref = useRef() useEffect(() => { if (ref && ref.current && ref.current.clientHeight) { console.log('called') } console.log('useEffect', { ref, current: ref.current, clientHeight: ref.current.clientHeight, }) }, []) return ( <img ref={ref} className="depth-reference-bar" src={DepthRuler} alt="no ruler found" /> ) }
The problem with this is that it returns the clientHeight as 0 but console.log in useEffect has the correct clientHeight as shown in below pic.
This means that ref && ref.current && ref.current.clientHeight
is not defined when called but consoling in same useEffect is showing correct value for ref
, current: ref.current
but clientHeight: ref.current.clientHeight
is ZERO.
Similarly, I can’t use ....}, [ref && ref.current && ref.current.clientHeight]
in useEffect
because useEffect
do not accept complex expression. If I defined a variable outside or inside useEffect
as const clientHeight = (ref && ref.current && ref.current.clientHeight) || 0
, no luck!
Can anyone help in this regards. Thanks!
Advertisement
Answer
As others mentioned here, your logic happens before image is loaded in most cases. So you have to get the image dimensions after the image has loaded because the browser doesn’t know the image dimensions before that.
I know you mentioned you want to do it with hooks, but unless you are doing something reusable, there’s probably no need for hooks here. Or unless you are trying to understand them better, then it’s fine.
One option would be to just use the onLoad
event on the image element. This way you don’t have to do all these checks if you have something in ref.current
or is img.complete === true
.
import React from 'react' const DepthChartContent = props => { const handleImageLoad = (event) => { // Do whatever you want here const imageHeight = event.target.clientHeight; } return ( <img ref={ref} className="depth-reference-bar" src={DepthRuler} alt="no ruler found" onLoad={handleImageLoad} /> ) }
Don’t get me wrong, I absolutely love hooks, but they aren’t always the solution.