@rehooks/component-size
Advanced tools
Comparing version 1.0.1 to 1.0.2
@@ -6,2 +6,2 @@ interface ComponentSize { | ||
export default function useComponentSize(): ComponentSize | ||
export default function useComponentSize<T = any>(ref: React.RefObject<T>): ComponentSize |
64
index.js
'use strict' | ||
let { useState, useLayoutEffect } = require('react') | ||
let { useCallback, useState, useLayoutEffect } = require('react') | ||
function getSize(el) { | ||
if (!el) { | ||
return {} | ||
return { | ||
width: 0, | ||
height: 0 | ||
} | ||
} | ||
@@ -16,30 +19,41 @@ | ||
function useComponentSize(ref) { | ||
let [ComponentSize, setComponentSize] = useState(getSize(ref.current)) | ||
let [ComponentSize, setComponentSize] = useState( | ||
getSize(ref ? ref.current : {}) | ||
) | ||
function handleResize() { | ||
if (ref && ref.current) { | ||
setComponentSize(getSize(ref.current)) | ||
} | ||
} | ||
const handleResize = useCallback( | ||
function handleResize() { | ||
if (ref.current) { | ||
setComponentSize(getSize(ref.current)) | ||
} | ||
}, | ||
[ref] | ||
) | ||
useLayoutEffect(() => { | ||
handleResize() | ||
useLayoutEffect( | ||
() => { | ||
if (!ref.current) { | ||
return | ||
} | ||
if (ResizeObserver) { | ||
let resizeObserver = new ResizeObserver(() => handleResize()) | ||
resizeObserver.observe(ref.current) | ||
handleResize() | ||
return () => { | ||
resizeObserver.disconnect(ref.current) | ||
resizeObserver = null | ||
if (typeof ResizeObserver === 'function') { | ||
let resizeObserver = new ResizeObserver(() => handleResize()) | ||
resizeObserver.observe(ref.current) | ||
return () => { | ||
resizeObserver.disconnect(ref.current) | ||
resizeObserver = null | ||
} | ||
} else { | ||
window.addEventListener('resize', handleResize) | ||
return () => { | ||
window.removeEventListener('resize', handleResize) | ||
} | ||
} | ||
} else { | ||
window.addEventListener('resize', handleResize) | ||
return () => { | ||
window.removeEventListener('resize', handleResize) | ||
} | ||
} | ||
}, []) | ||
}, | ||
[ref.current] | ||
) | ||
@@ -46,0 +60,0 @@ return ComponentSize |
{ | ||
"name": "@rehooks/component-size", | ||
"version": "1.0.1", | ||
"version": "1.0.2", | ||
"description": "React hook for component-size", | ||
@@ -28,2 +28,3 @@ "main": "index.js", | ||
"devDependencies": { | ||
"@types/react": "^16.4.18", | ||
"ava": "^0.25.0", | ||
@@ -30,0 +31,0 @@ "browser-env": "^3.2.5", |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5603
56
8