loading words...

Mar 12, 2019 08:44:17

measuring elements with react hooks

by @swizecteller | 210 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

Last night I figured out how to measure DOM dimensions with React Hooks. I'm sure it's been covered before but I had fun finding out. #200wordsTIL

```

const MyComponent = () => {

const targetRef = useRef();

const [dimensions, setDimensions] = useState({})

useLayoutEffect(() => {

setDimensions(targetRef.current.getClientBoundingRect());

}, [targetRef.current])

return <div ref={targetRef}>{*/ all my stuff */}</div>

}

```

---

Doesn't look like much but it's handy for data visualization. Especially when you want to align things with other things.

I used a few of those snippets to position a curved line on this stepper

---

Here's how it works:

- useRef creates a React.ref, lets you access the DOM

- useState gives you place to store/read the result

- useLayoutEffect runs before browser paint but after all is known

- getClientBoundingRect() measures a DOM node. Width, height, x, y, etc

- render div with correct ref

---

You can make the above easier to use with a custom hook like this

useDimensions returns the measurements and a ref. Use as before :)

```

function useDimensions() {

const ref = useRef();

const [dimensions, setDimensions] = useState({})

useLayoutEffect(() => {

setDimensions(targetRef.current.getClientBoundingRect());

}, [targetRef.current])

return { ref, ...dimensions }

}

const MyComponent = () => {

const { ref, width, height } = useDimensions();

return <div ref={ref}>{*/ all my stuff */}</div>

}

```

---

Hm maybe I should open source this snippet 🤔

Wonder if anyone would use it

Originally published at twitter.com

contact: email - twitter / Terms / Privacy