Skip to content

Commit

Permalink
(feat) Add support for multiple ResizeObserverBoxOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
Gautam-Arora24 authored Sep 27, 2021
2 parents 0968c25 + e3d9630 commit a714e2c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# resize-observer-hook

<img src="https://user-images.githubusercontent.com/74927578/132028559-afdb6cd7-dc32-4d44-a91e-bf129f985b07.gif" height="400px"></img>

logo by [mehan](https://github.com/mehanalavimajd)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors-)

<!-- ALL-CONTRIBUTORS-BADGE:END -->

> A hook that uses Resize Observer API to monitor changes in the size of an element.
Expand Down Expand Up @@ -34,6 +36,22 @@ const App = () => {
}
```

You can add multiple `ResizeObserverBoxOptions` to the useResizeObserver like this ->

```
const [ref,width,height] = useResizeObserver("borderBoxSize");
```

`ResizeObserverBoxOptions` that are supported currently in the library ->

- **borderBoxSize**
- **contentBoxSize**
- **contentRect**

Note ⚠️ - Some options aren't supported in some broswers so if you provide any option that is not being supported in your current browser, it will automatically use `contentRect` to calculate height and width of the observed element.

See more details over here -> https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry

<img src='./media/example.gif'></img>

## Contributing
Expand Down
24 changes: 20 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef } from 'react'

const useResizeObserver = () => {
const useResizeObserver = (option = 'contentRect') => {
const ref = useRef(null)
const [height, setHeight] = useState()
const [width, setWidth] = useState()
Expand All @@ -17,12 +17,28 @@ const useResizeObserver = () => {
observer.disconnect()
}
}
}, [ref])
})

const handleResize = (entries) => {
for (let entry of entries) {
setHeight(entry.contentRect.height)
setWidth(entry.contentRect.width)
if (
option === 'borderBoxSize' &&
entry.borderBoxSize &&
entry.borderBoxSize.length > 0
) {
setHeight(entry.borderBoxSize[0].blockSize)
setWidth(entry.borderBoxSize[0].inlineSize)
} else if (
option === 'contentBoxSize' &&
entry.contentBoxSize &&
entry.contentBoxSize.length > 0
) {
setHeight(entry.contentBoxSize[0].blockSize)
setWidth(entry.contentBoxSize[0].inlineSize)
} else {
setHeight(entry.contentRect.height)
setWidth(entry.contentRect.width)
}
}
}

Expand Down

0 comments on commit a714e2c

Please sign in to comment.