All Projects β†’ Swizec β†’ Usedimensions

Swizec / Usedimensions

A React Hook to measure DOM nodes

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Usedimensions

Clean React
Sistema em ReactJs usando Hooks, Typescript, TDD, Clean Architecture, Design Patterns e SOLID principles
Stars: ✭ 408 (-24.02%)
Mutual labels:  hooks
The Platform
Web. Components. πŸ˜‚
Stars: ✭ 4,355 (+710.99%)
Mutual labels:  hooks
Mobx Router
A simple router for MobX + React apps
Stars: ✭ 489 (-8.94%)
Mutual labels:  hooks
Relay Hooks
Use Relay as React hooks
Stars: ✭ 423 (-21.23%)
Mutual labels:  hooks
Beautiful React Hooks
πŸ”₯ A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development πŸ”₯
Stars: ✭ 5,242 (+876.16%)
Mutual labels:  hooks
React Use Gesture
πŸ‘‡Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
Stars: ✭ 5,704 (+962.2%)
Mutual labels:  hooks
React Native Version
πŸ”’ Version your React Native or Expo app in a `npm version` fashion.
Stars: ✭ 408 (-24.02%)
Mutual labels:  hooks
React Hooks
Essential set of React Hooks for convenient Web API consumption and state management.
Stars: ✭ 515 (-4.1%)
Mutual labels:  hooks
React Recipes
πŸ‘©β€πŸ³ A React Hooks utility library containing popular customized hooks
Stars: ✭ 452 (-15.83%)
Mutual labels:  hooks
Atomico
Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.
Stars: ✭ 481 (-10.43%)
Mutual labels:  hooks
Openpbs
An HPC workload manager and job scheduler for desktops, clusters, and clouds.
Stars: ✭ 427 (-20.48%)
Mutual labels:  hooks
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+742.64%)
Mutual labels:  hooks
Winxp
🏁 Web based Windows XP desktop recreation.
Stars: ✭ 4,717 (+778.4%)
Mutual labels:  hooks
Use Scroll Position
Use scroll position ReactJS hook done right
Stars: ✭ 414 (-22.91%)
Mutual labels:  hooks
Maily
πŸ“« Rails Engine to preview emails in the browser
Stars: ✭ 502 (-6.52%)
Mutual labels:  hooks
Release It
πŸš€ Automate versioning and package publishing
Stars: ✭ 4,773 (+788.83%)
Mutual labels:  hooks
React Hooks Lib
A set of reusable React Hooks.
Stars: ✭ 460 (-14.34%)
Mutual labels:  hooks
React Hooks Cheatsheet
πŸ¦– React hooks cheatsheet with live editable examples
Stars: ✭ 520 (-3.17%)
Mutual labels:  hooks
Animavita
Trigger life-saving alerts, register animals for adoption and find the closest pet friend to adopt 🐢
Stars: ✭ 508 (-5.4%)
Mutual labels:  hooks
React Hook
↩ Strongly typed, concurrent mode-safe React hooks
Stars: ✭ 472 (-12.1%)
Mutual labels:  hooks

useDimensions - a React Hook to measure DOM nodes

Travis npm package Coveralls

Demo

πŸ‘‰ check out demo page to see useDimensions in action

Backstory :P

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.

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

useDimensions hook

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
or
$ npm install --save react-use-dimensions

Using it in a component looks like this

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</div>;
};

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.

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>
            <div ref={stepRef}>This is a step</div>
            <h1 ref={titleRef}>The title</h1>
        </div>
    );
};

Disabling live updates

By default useDimensions live updates its measurements on every scroll and resize event. This can lead to a lot of re-rendering, if you aren't careful.

I recommend feeding the dimensions you care about into your list of useEffect triggers. That is the best way to ensure good performance.

If however, you don't want that and know you just need to measure once, useDimensions supports an optional liveMeasure argument.

const MyComponent = () => {
    const [stepRef, stepSize] = useDimensions({ liveMeasure: false });

    // useDimensions never updates and won't trigger re-renders
    console.log("Step is at X: ", stepSize.x);

    return (
        <div>
            <div ref={stepRef}>This is a step</div>
        </div>
    );
};

License

MIT License of course.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].