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!