Swizec Teller - a geek with a hatswizec.com

    useDimensions – a React Hook to measure DOM nodes

    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.

    Swizec Teller published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@Swizec
    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
    Tweet media

    SVG in the background detects position of itself, positions of the title and circle, and uses those to define the start and end line of my curve. πŸ‘Œ

    Many ways you can do this.

    @lavrton linked to a list of existing NPM packages that sort of do it. @mcalus shared how he uses react-sizeme to get it done.

    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

    Swizec Teller published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@Swizec
    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
    Tweet media

    useDimensions hook

    This seemed like a neat approach so I turned it into an open source React Hook. You might enjoy it.

    useDimensions source
    useDimensions source

    useDimensions source

    Yep that's it. It really is that simple.

    πŸ‘‰ GitHub link

    • 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
    • toJSON turns a DOMRect object into a plain object so you can destructure

    Here's how to use it in your project πŸ‘‡

    First, add useDimensions to your project

    $ yarn add react-use-dimensions
    $ npm install --save react-use-dimensions

    Using it in a component looks like this

    <code class="javascript">import React from 'react';
    import useDimensions from 'react-use-dimensions';
    const MyComponent = () => {
    const [ref, { x, y, width }] = useDimensions();
    return (
    <div ref={ref}>
    This is the element you'll measure

    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.

    <code class="javascript">const MyComponent = () => {
    const [stepRef, stepSize] = useDimensions();
    const [titleRef, titleSize] = useDimensions();
    console.log("Step is at X: ", stepSize.x);
    console.log("Title is", titleSize.width, "wide");
    return (
    <div ref={stepRef}>This is a step</div>
    <h1 ref={titleRef}>The title</h1>

    MIT License of course.

    Consider retweeting if you think it's neat

    Swizec Teller published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@Swizec
    πŸ”₯useDimensions is now an open source react hook πŸ”₯

    πŸ™ GitHub -->
    ✍ short blog -->

    Simple and works great πŸ‘Œ
    Tweet media

    Enjoy ✌️ ~Swizec

    Did you enjoy this article?

    Published on March 13th, 2019 in Front End, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works πŸ‘‡

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters πŸ’Œ on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open 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. πŸ‘Œ"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer?Β I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    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

    Want to brush up on your modern JavaScript syntax?Β Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❀️

    Created bySwizecwith ❀️