Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  67] [ 1]  / answers: 1 / hits: 17584  / 4 Years ago, mon, may 18, 2020, 12:00:00

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.



ref-console-image



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!


More From » reactjs

 Answers
78

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.


[#50942] Friday, May 8, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dawnc

Total Points: 612
Total Questions: 94
Total Answers: 98

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
dawnc questions
Fri, Nov 26, 21, 00:00, 3 Years ago
Wed, Jul 15, 20, 00:00, 4 Years ago
Sun, Dec 15, 19, 00:00, 5 Years ago
Thu, May 30, 19, 00:00, 5 Years ago
;