GithubHelp home page GithubHelp logo

wellyshen / react-cool-dimensions Goto Github PK

View Code? Open in Web Editor NEW
945.0 3.0 20.0 3.61 MB

๐Ÿ˜Ž ๐Ÿ“ React hook to measure an element's size and handle responsive components.

Home Page: https://react-cool-dimensions.netlify.app

License: MIT License

TypeScript 73.76% JavaScript 8.02% Shell 0.44% HTML 10.25% SCSS 7.53%
react hook dimensions measure size resizeobserver responsive-components container-queries performance typescript

react-cool-dimensions's Introduction

REACT COOL DIMENSIONS

A React hook that measure an element's size and handle responsive components with highly-performant way, using ResizeObserver. Try it you will ๐Ÿ‘๐Ÿป it!

โค๏ธ it? โญ๏ธ it on GitHub or Tweet about it.

build status coverage status npm version npm downloads npm downloads gzip size All Contributors PRs welcome Twitter URL

demo

โšก๏ธ Try yourself: https://react-cool-dimensions.netlify.app

Features

Requirement

To use react-cool-dimensions, you must use [email protected] or greater which includes hooks.

Installation

This package is distributed via npm.

$ yarn add react-cool-dimensions
# or
$ npm install --save react-cool-dimensions

Usage

react-cool-dimensions has a flexible API design, it can cover simple to complex use cases for you. Here are some examples to show you how does it work.

โš ๏ธ Most modern browsers support ResizeObserver natively. You can also use polyfill for full browser support.

Basic Use Case

To report the size of an element by the width and height states.

import useDimensions from "react-cool-dimensions";

const App = () => {
  const { observe, unobserve, width, height, entry } = useDimensions({
    onResize: ({ observe, unobserve, width, height, entry }) => {
      // Triggered whenever the size of the target is changed...

      unobserve(); // To stop observing the current target element
      observe(); // To re-start observing the current target element
    },
  });

  return (
    <div ref={observe}>
      Hi! My width is {width}px and height is {height}px
    </div>
  );
};

๐Ÿ’ก You don't have to call unobserve when the component is unmounted, this hook will handle it for you.

Responsive Components

We have media queries but those are based on the browser viewport not individual elements. In some cases, we'd like to style components based on the width of a containing element rather than the browser viewport. To meet this demand there's a proposal for container queries, but it still doesn't exist today...

No worries, react-cool-dimensions provides an alternative solution for us! We can activate the responsive mode by the breakpoints option. It's a width-based solution, once it's activated we can easily apply different styles to a component according to the currentBreakpoint state. The overall concept as below.

If you wish to update the state on the breakpoints changed, you can set the updateOnBreakpointChange option to true.

import useDimensions from "react-cool-dimensions";

const Card = () => {
  const { observe, currentBreakpoint } = useDimensions({
    // The "currentBreakpoint" will be the object key based on the target's width
    // for instance, 0px - 319px (currentBreakpoint = XS), 320px - 479px (currentBreakpoint = SM) and so on
    breakpoints: { XS: 0, SM: 320, MD: 480, LG: 640 },
    // Will only update the state on breakpoint changed, default is false
    updateOnBreakpointChange: true,
    onResize: ({ currentBreakpoint }) => {
      // Now the event callback will be triggered when breakpoint is changed
      // we can also access the "currentBreakpoint" here
    },
  });

  return (
    <div class={`card ${currentBreakpoint}`} ref={observe}>
      <div class="card-header">I'm ๐Ÿ˜Ž</div>
      <div class="card-body">I'm ๐Ÿ‘•</div>
      <div class="card-footer">I'm ๐Ÿ‘Ÿ</div>
    </div>
  );
};

Note: If the breakpoints option isn't set or there's no the defined breakpoint (object key) for a range of width. The currentBreakpoint will be empty string.

Conditionally Updating State

You can use the shouldUpdate option to conditionally update the state to reduce unnecessary re-renders as below.

const returnObj = useDimensions({
  shouldUpdate: ({ currentBreakpoint, width, height, entry }) => {
    // Will only update the state when the target element's width greater than 300px
    return state.width > 300;
  },
});

Note: When updateOnBreakpointChange and shouldUpdate are used at the same time, shouldUpdate has a higher priority.

Border-box Size Measurement

By default, the hook reports the width and height based on the content rectangle of the target element. We can include the padding and border for measuring by the useBorderBoxSize option. Please note, the width and height states are rely on the ResizeObserverEntry.borderBoxSize but it hasn't widely implemented by browsers therefore we need to use polyfill for this feature.

import useDimensions from "react-cool-dimensions";
import { ResizeObserver } from "@juggle/resize-observer";

const App = () => {
  const { observe, width, height } = useDimensions({
    useBorderBoxSize: true, // Tell the hook to measure based on the border-box size, default is false
    polyfill: ResizeObserver, // Use polyfill to make this feature works on more browsers
  });

  return (
    <div
      style={{
        width: "100px",
        height: "100px",
        padding: "10px",
        border: "5px solid grey",
      }}
      ref={observe}
    >
      {/* Now the width and height will be: 100px + 10px + 5px = 115px */}
      Hi! My width is {width}px and height is {height}px
    </div>
  );
};

How to Share A ref?

You can share a ref as follows:

import { useRef } from "react";
import useDimensions from "react-cool-dimensions";

const App = () => {
  const ref = useRef();
  const { observe } = useDimensions();

  return (
    <div
      ref={(el) => {
        observe(el); // Set the target element for measuring
        ref.current = el; // Share the element for other purposes
      }}
    />
  );
};

Performance Optimization

The onResize event will be triggered whenever the size of the target element is changed. We can reduce the frequency of the event callback by activating the responsive mode or implementing our own throttled/debounced function as below. Note that in order to throttle/debounce the function correctly, it will need to be memorized else it will be recreated on every render call.

import { useMemo } from "react";
import _ from "lodash";

const returnObj = useDimensions({
  onResize: useMemo(
    () =>
      _.throttle(() => {
        // Triggered once per every 500 milliseconds
      }, 500),
    []
  ),
});

Working in TypeScript

This hook supports TypeScript, you can tell the hook what type of element you are going to observe through the generic type:

const App = () => {
  const { observe } = useDimensions<HTMLDivElement>();

  return <div ref={observe} />;
};

๐Ÿ’ก For more available types, please check it out.

API

const returnObj = useDimensions(options?: object);

Return object

It's returned with the following properties.

Key Type Default Description
observe function To set a target element for measuring or re-start observing the current target element.
unobserve function To stop observing the current target element.
width number or null null The width of the target element in pixel. Null while target has not mounted.
height number or null null The height of the target element in pixel. Null while target has not mounted.Z
currentBreakpoint string Indicates the current breakpoint of the responsive components.
entry object The ResizeObserverEntry of the target element.

Parameter

The options provides the following configurations and event callback for you.

Key Type Default Description
breakpoints object Activates the responsive mode for responsive components or performance optimization.
updateOnBreakpointChange boolean false Tells the hook to update the state on breakpoint changed.
useBorderBoxSize boolean false Tells the hook to measure the target element based on the border-box size.
shouldUpdate function Tells the hook to conditionally update the state.
onResize function It's invoked whenever the size of the target element is changed. But in responsive mode, it's invoked based on the changing of the breakpoint rather than the size.
polyfill ResizeObserver It's used for injecting a polyfill.

ResizeObserver Polyfill

ResizeObserver has good support amongst browsers, but it's not universal. You'll need to use polyfill for browsers that don't support it. Polyfills is something you should do consciously at the application level. Therefore react-cool-dimensions doesn't include it.

We recommend using @juggle/resize-observer:

$ yarn add @juggle/resize-observer
# or
$ npm install --save @juggle/resize-observer

Then inject it by the polyfill option:

import { ResizeObserver } from "@juggle/resize-observer";

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

Or pollute the window object:

import { ResizeObserver, ResizeObserverEntry } from "@juggle/resize-observer";

if (!("ResizeObserver" in window)) {
  window.ResizeObserver = ResizeObserver;
  // Only use it when you have this trouble: https://github.com/wellyshen/react-cool-dimensions/issues/45
  // window.ResizeObserverEntry = ResizeObserverEntry;
}

You could use dynamic imports to only load the file when the polyfill is required:

(async () => {
  if (!("ResizeObserver" in window)) {
    const module = await import("@juggle/resize-observer");
    window.ResizeObserver = module.ResizeObserver;
    // Only use it when you have this trouble: https://github.com/wellyshen/react-cool-dimensions/issues/45
    // window.ResizeObserverEntry = module.ResizeObserverEntry;
  }
})();

Articles / Blog Posts

๐Ÿ’ก If you have written any blog post or article about react-cool-dimensions, please open a PR to add it here.

Contributors โœจ

Thanks goes to these wonderful people (emoji key):

Welly
Welly

๐Ÿ’ป ๐Ÿ“– ๐Ÿšง
Runar Kristoffersen
Runar Kristoffersen

๐Ÿ“– ๐Ÿ’ป ๐Ÿค”
Ricardo Amaral
Ricardo Amaral

๐Ÿ’ป
Cornelius
Cornelius

๐Ÿ›
Joseph Horton
Joseph Horton

๐Ÿ“–
sirkrisp
sirkrisp

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

react-cool-dimensions's People

Contributors

allcontributors[bot] avatar cornelius-behrend avatar dependabot-preview[bot] avatar dependabot[bot] avatar jhrtn avatar rfgamaral avatar sirkrisp avatar wellyshen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-cool-dimensions's Issues

Doesn't handle component mounted after start

Bug Report

Describe the Bug

If the ref.current is undefined the first pass through, we'll not set up the observer, and we won't re-run this effect if the ref.current changes (only if the ref itself changes), so in this case we'll never get the width and height for an element.

How to Reproduce

An easy way to reproduce this is to try to measure the dimensions of an element that mounts after the initial render:

const { ref, width, height } = useDimensions();
const [ showBox, setShowBox ] = useState(false);

return <div>
  <button onClick={() => setShowBox(true)}>Show!</button>
  { showBox && <div ref={ref}>Tada! {width}x{height}</div> }
</div>;

Expected Behavior

Should get the width and height of the element.

Additional Information

This is why a lot of similar libraries don't let you pass in a ref - they return a ref to you which is really a (el: HTMLElement) => void, and when it gets called they can handle the initial mounting of the component.

Type validation issue with tsc: onResize: Type 'T' does not satisfy the constraint 'HTMLElement'.

Bug Report

Describe the Bug

I'm getting a type validation issue when running tsc:

48     onResize?: OnResize<T>;
                           ~
node_modules/react-cool-dimensions/dist/index.d.ts:52:42 - error TS2344: Type 'T' does not satisfy the constraint 'HTMLElement'.

52   interface Return<T> extends Omit<Event<T>, "entry"> {

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Install latest version of react-cool-dimensions
  2. Use this code:
const onResize = ({ width }: { width: number}) => {
    if (ref.current) {
      ref.current.width = width
    }
  }

  const { observe, width, height } = useDimensions<HTMLDivElement>({
    onResize,
  })
  1. Run tsc
  2. See error

Expected Behavior

As far as I can tell you don't have any typed examples with onResize in the demo folder, so i'm not sure if i'm doing something wrong.

Screenshots

image

image

Your Environment

  • Device: Macbook Pro
  • OS: macOS
  • Version: 1.3.2 and Node v14.15.0

Set Resize Obeserver box

Bug Report

I need to be able to set the box that resize observers uses

Describe the Bug

Right now I can't get it to respect box-sizing: border-box

How to Reproduce

Try to size an element with box-sizing: border-box

Expected Behavior

Should be able to make it take padding into account

Infinite height increase

Bug Report

In scenarios where the observed div should take up all available space (height and width at 100%), I find that the height reported by react-cool-dimensions increases infinitely...

StackblitzLink

https://stackblitz.com/edit/cool-dims-height

Expected Behavior

The orange box should not resize independently of the window being resized

Losing track of element with conditional rendering

Bug Report

Describe the Bug

I have this element that I need to track its dimensions and react-cool-dimensions works nicely for what I want to achieve, the problem is that this element is not always rendered and it looks like useDimensions loses track of the element reference.

If that didn't make sense, please see below...

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Go to https://codesandbox.io/s/beautiful-haslett-sfhji
  2. A red box is loaded and its dimensions are reported correctly
  3. Click the TOGGLE button to switch to a blue box instead
  4. The red box dimensions are now reported to be 0
  5. Click the TOGGLE button to switch back to the red box
  6. The red box dimensions remain 0

Expected Behavior

The red box dimensions should be correctly reported in step 6 above.

Additional Information

  • The red box is resizable if it helps to test this
  • There's another third-party hook commented out where this problem does not exist

Error with React testing library

Bug Report

I`m using ResizeObserver Polyfill for testing with React testing library, tests passed successfully, but still have a console.error:

setupTests.ts

import { ResizeObserver } from '@juggle/resize-observer';

window.ResizeObserver = ResizeObserver;
Element.prototype.scrollTo = jest.fn();

Error:

console.error
๐Ÿ’ก react-cool-dimensions: the browser doesn't support Resize Observer, please use polyfill: https://github.com/wellyshen/react-cool-dimensions#resizeobserver-polyfill

  at node_modules/react-cool-dimensions/dist/index.js:1:2420
  at invokePassiveEffectCreate (node_modules/react-dom/cjs/react-dom.development.js:23487:20)
  at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
  at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
  at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
  at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
  at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
  at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)

Your Environment

"react": "^17.0.2",
"@testing-library/jest-dom": "^5.11.4"
"@testing-library/react": "^11.1.0"
"react-cool-dimensions": "1.3.4"

ResizeObserver loop limit exceeded

Ever since that we started using react-cool-dimensions that we've been having a lot of logged errors:

ResizeObserver loop limit exceeded

Based on this StackOverflow answer it's not really something to worry about, however, it can be improved by wrapping the ResizeObserver updates in a requestAnimationFrame.

Here's an example of how a similar library (not a hook) solved this.

Do you think we can get such an improvement into react-cool-dimensions?

useDimensions is not a function

Issue

In my open-source library ( reaviz.dev ), we use this project to measure the chart. In some instances ( such as code sandbox ), I get the following error. You can also live see the error here: https://codesandbox.io/p/sandbox/funny-currying-s7wgcn?file=%2Findex.js&from-embed=

TypeError
useDimensions is not a function
ChartContainer
https://s7wgcn.csb.app/node_modules/reaviz/dist/index.umd.cjs:2112:40
renderWithHooks
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:15486:18
mountIndeterminateComponent
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:20103:13
beginWork
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:21626:16
HTMLUnknownElement.callCallback
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:4164:14
Object.invokeGuardedCallbackDev
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:4213:16
invokeGuardedCallback
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:4277:31
beginWork$1
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:27490:7
performUnitOfWork
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:26596:12
workLoopSync
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:26505:5
renderRootSync
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:26473:7
performSyncWorkOnRoot
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:26124:20
flushSyncCallbacks
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:12042:22
flushSync
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:26240:7
legacyCreateRootFromDOMContainer
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:29614:5
legacyRenderSubtreeIntoContainer
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:29640:12
Object.render
https://s7wgcn.csb.app/node_modules/react-dom/cjs/react-dom.development.js:29731:10
$csb$eval
/index.js:18:9

Here is where I'm leverage the library: https://github.com/reaviz/reaviz/blob/master/src/common/containers/ChartContainer.tsx#L100

Its worth noting this doesn't get thrown all the time, just in some instances ( I haven't figured out what exactly this instance is that causes it though ). Have you seen this before?

Versions

"react-cool-dimensions": "^3.0.1",

useBorderBoxSize and polyfill not working on Safari

Bug Report

Describe the Bug

Using useBorderBoxSize: true and polyfill: ResizeObserver with Safari 13/14 does not seem to work.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Go to the CodeSandbox below and scroll the main content area
  2. Observe that on Firefox/Chrome/Edge everything works as expected:
    • Light blue headers correctly sticky below the coral header โœ”
  3. Observe that on Safari it doesn't work as expected:
    • Light blue headers wrongly sticky behind the coral header โŒ

CodeSandbox Link

Expected Behavior

  • Light blue headers should correctly sticky below the coral header in all browsers Firefox/Chrome/Edge/Safari

Add `ref` to`Return`

Feature Request

Describe the Feature

Since ref is always required, react-cool-dimensions should provide that as part of its API.

Describe the Solution You'd Like

react-cool-dimensions creates ref internally and returns it as part of Return, which the consumer then attaches to their container.

Using the "Basic Use Case" from README, it'd look like this:

const App = () => {
  const { ref, width, height, entry, unobserve, observe } = useDimensions({
    onResize: ({ width, height, entry, unobserve, observe }) => {
      // Triggered whenever the size of the target is changed
    },
  });

  return (
    <div ref={ref}>
      Hi! My width is {width}px and height is {height}px
    </div>
  );
};

Additional Information

Obviously not something that's all that important, but it makes the API a little cleaner and easier to use.

ResizeObserver - loop limit exceeded

Bug Report

Describe the Bug

Since Chrome 64, the ResizeObserver is firing a silent error that might be captured and raised when adding an event listener to the window (like some UI error handlers do).

See this GitHub discussion.

In index.ts, this can be fixed as follows:

// eslint-disable-next-line compat/compat
    observerRef.current = new (polyfill || window.ResizeObserver)(
      ([entry]: any) => {
        window.requestAnimationFrame(() => { /* < New line */

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Use Chrome 64 / Safari 14 or newer
  2. window.addEventListener('error', function(e) { console.log(e); }); to log the error

Screenshot

Bildschirmfoto 2021-06-07 um 17 17 22

Expected Behavior

No errors from ResizeObserver should be forwarded to the event listeners.

Your Environment

  • Device: [MacBook Pro]
  • OS: [macOS 11.4]
  • Browser: [Chrome, Safari]
  • Version: [91.0.4472.77, 14.1.1]

Custom resize handlers

Feature Request

Describe the Feature

First, good job with the library! It works flawlessly!
I would like to use it in a style guide i'm building, and would be nice to be able to first, define the places where the resize handler will be available (right, top, left, bottom, top-right..)
And on top of that, be able to pass a custom component to handle the resize (instead of the circle you currently have in the bottom-right corner).
Do you think is possible to do?
If it is and you are busy, I can try to work on that and do a PR.

Additional Information

I'm currently using this one https://github.com/bokuweb/re-resizable, which gives you a handleComponent attribute to override the handlers.

just observe window?

Feature Request

I was thinking that it was possible to observe window size but apparently it's not even possible. This would be handy for any stuff to keep in sync with window dimension.

ResizeObserver polyfill does not register in hook when loaded onto window

Bug Report

Describe the Bug

When importing a ResizeObserver polyfill and assigning to window.ResizeObserver, the useDimensions hook does not seem to be registering the polyfill and thus does not work.

How to Reproduce

I've tried both methods of loading the polyfill onto the window object:
asynchronously

 const isResizeObserverSupported = "ResizeObserver" in window;
 if (!isResizeObserverSupported) {
    const module = await import("@juggle/resize-observer");
    (window as any).ResizeObserver = module.ResizeObserver; 
}

synchronously

const isResizeObserverSupported = "ResizeObserver" in window;
if (!isResizeObserverSupported) {
  (window as any).ResizeObserver = ResizeObserver; // eslint-disable-line
}

Both of these on an unsupported browser will result in the hook returning 0 for all dimensions and complaining that ResizeObserver is not supported.

When importing the polyfill (async or sync) and directly providing it through the hook's polyfill option, it works properly.

Expected Behavior

Adding the polyfill through the window object should cause the hook to work.

Your Environment

  • OS: macOS 10.15.4 (Catalina)
  • Browser Firefox 68 (ResizeObserver unsupported)
  • Version of react-cool-dimensions: v0.6.1

width and height typing of Return object

Hello,

I've noticed a discrepancy between the documentation and the actual typing of the Return interface.
In the documentation it says that as of version 3.0.0 the width and height are initially null. But looking at index.d.ts, the types of width and height are number but should instead be number | null.

Can you please look into this?
Thank you ๐Ÿ‘‹

Only update state on breakpoint

Feature Request

Describe the Feature

When using breakpoints, it may be desirable to only receive updates if the breakpoint changes, and not on tiny changes to width/height etc.

Describe the Solution You'd Like

I would like to add a flag to the options of the hook, onlyUpdateOnBreakpointChange, which only updates state if the breakpoint is changed from the previous state.

Also, to make this option very configurable, a second option is provided, customSetState for more advanced use-cases where the developer wants more control of when the state is updated based on any logic. For instance, only update if the delta-width is more than 50px.

Describe Alternatives You've Considered

I've looked at using debounce, but it only sort of helps.

Additional Information

PR is submitted as a proposal.

Multiple Refs

How would I use this to keep track of multiple refs of a component? I want to keep track of the width of multiple items that could change over time based on props. Is it possible with this package? I'm aware you can call the hook multiple times but the data I need to track is dynamic and you can't really call hooks in a loop.

react-cool-dimensions shows 0 width & 0 height on mobile browsers

Bug Report

react-cool-dimensions shows 0 width & 0 height on mobile browsers. it works fine in desktop, but not mobile.

How to Reproduce

  1. create react app (npx create-react-app my-app)
  2. install react-cool-dimensions (cd my-app && npm i -S react-cool-dimensions)
  3. use react-cool-dimensions to display width & height of element(s) (i.e., <header>, <footer>

Code demonstrating bug

import React, { useRef } from "react";
import useDimensions from "react-cool-dimensions";

function App() {
  const headRef = useRef();
  const footRef = useRef();
  const { height: headHeight, width: headWidth } = useDimensions({
    ref: headRef,
    useBorderBoxSize: true,
  });
  const { height: footHeight, width: footWidth } = useDimensions({
    ref: footRef,
    useBorderBoxSize: false,
  });
  return (
    <div>
      <header ref={headRef}>this is the header</header>
      <main>this is main</main>
      <footer ref={footRef}>
        this is footer
        <br />
        headWidth: {headWidth}
        <br />
        headHeight: {headHeight}
        <br />
        footWidth: {footWidth}
        <br />
        footHeight: {footHeight}
      </footer>
    </div>
  );
}

export default App;

react-cool-dim-test-main.zip

Expected Behavior

header & footer width & height should not be 0 on mobile.

Screenshots

Desktop:

desktop-browser

Mobile:

mobile-browser

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.