Get element height or width using ReactJs hook
The following hook can be used to get the dimension of an element:
import { useState, useLayoutEffect } from 'react'
export default function useDimensions(ref) {
const [dimensions, setDimensions] = useState({})
useLayoutEffect(() => {
setDimensions(ref.current.getBoundingClientRect().toJSON())
}, [ref.current])
return [dimensions, ref]
}
To use the above hook, proceed as follows:
export default function Articles({ articles }) {
const articleListRef = useRef()
const [dimensions] = useDimensions(articleListRef)
const { height } = dimensions
const onArticleClick = () => {
if (typeof window !== 'undefined' && height > 300) {
window.scrollTo({ top: height, behavior: 'smooth' })
}
}
return (
<div className="article-list" onClick={onArticleClick} ref={articleListRef}>
{articles.map((article) => {
return (
<Tile
article={article}
key={article.slug}
highlighted={article.slug === articleId}
/>
)
})}
</div>
)
}
NOTE: The typeof window !== 'undefined'
check is only needed while using the hook in Next.js