Yes it's new, I just open sourced it 😛
The other day I wanted to measure some DOM nodes. This is useful when you have to align items, or respond to browser width, or ... lots of reasons okay.
I had to align a curvy line with elements that aren't under my control. This little stepper component uses flexbox to evenly space circles, CSS layouting aligns the title, and you see where this is going.
Doesn't look like much but it's handy for data visualization. Especially when you want to align things with other things.— Swizec Teller published ServerlessHandbook.dev (@Swizec) March 12, 2019
I used a few of those snippets to position a curved line on this stepper pic.twitter.com/W9RLizRLPG
SVG in the background detects position of itself, positions of the title and circle, and uses those to define the
end line of my curve. 👌
Many ways you can do this.
All great, but I wanted something even simpler. I also didn't know about them and kind of just wanted to make my own.
Here's an approach I found works great
This seemed like a neat approach so I turned it into an open source React Hook. You might enjoy it.
Yep that's it. It really is that simple.
useRefcreates a React.ref, lets you access the DOM
useStategives you place to store/read the result
useLayoutEffectruns before browser paint but after all is known
getClientBoundingRect()measures a DOM node. Width, height, x, y, etc
toJSONturns a DOMRect object into a plain object so you can destructure
Here's how to use it in your project 👇
useDimensions to your project
$ yarn add react-use-dimensionsor$ npm install --save react-use-dimensions
Using it in a component looks like this
useDimensions returns a 2-element array. First the
ref, second the dimensions.
This is so multiple
useDimensions hooks in the same component don't step on each others' toes. Create as many refs and measurement objects as you'd like.
MIT License of course.
Consider retweeting if you think it's neat
Enjoy ✌️ ~Swizec
Here's how it works 👇
Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️