React Hooks: useDims

Here's another helpful React hook. This one returns the dimensions of an element that's passed to it.

It can be used in a component like this.

Let's break it down a bit. We start by receiving a ref and an optional boolean of isSvg. Since svgs use a different function to calculate size we can use this flag to differentiate.

Our hook is using a default dimension object in state with all values set to zero. We then return that dim if there aren't any changes.

Next, we have useEffect which does the heavy lifting. We're checking to see if we have a value in the ref and we are having useEffect watch the ref and isSvg.

Then, we have the calcs for the html and svg element. For the html element we can pull the offsets right off of the node. The svg, however, need to pass through getBBox() to get their dimensions.

Once it's all together we have a quick way to grab the dimensions from elements. You can also use it for multiple elements in the same component.

Categorydev
Discuss this article on Twitter