Git Product home page Git Product logo

wellyshen / react-cool-dimensions Goto Github PK

View Code? Open in Web Editor NEW
943.0 943.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%
container-queries dimensions hook measure performance react resizeobserver responsive-components size typescript

react-cool-dimensions's Introduction

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

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

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.

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 ๐Ÿ‘‹

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

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

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.

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 - 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]

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?

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

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

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.

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"

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

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",

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

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.