useComponentSize

useComponentSize gives you the size of your rendered component.

This is some example text
{}

Code for example above

import { useRef, useCallback, useEffect } from "react";
import { useComponentSize, SizeWrapper } from "@talves/use-component-size";
export const SizedComponent = () => {
const [value, setValue] = useState({});
return (
<div class="flex flex-col border-gray-400 border-2 p-2 m-5">
<SizeWrapper
class="border-secondary-300 border-2 p-2 m-5"
onSizeChange={(size) => setValue(size)}
>
{"This is some example text"}
</SizeWrapper>
<pre>{`${JSON.stringify(value, null, 2)}`}</pre>
</div>
);
};

Create a custom wrapper

Text for our custom size component wrapper
{}

Code for example above

Creating and using your own size wrapper:

import { useState, useRef, useCallback, useEffect } from "react";
import { useComponentSize } from "@talves/use-component-size";
import { usePrevious } from "@talves/use-previous";
function sizeEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
export const CustomSizeWrapper = ({ children, onSizeChange, ...props }) => {
const wrapperRef = useRef(null);
const componentSize = useComponentSize(wrapperRef); // A custom Hook
const previousSize = usePrevious(componentSize);
const handleSizeChange = useCallback(
(size) => {
if (typeof onSizeChange === "function") {
onSizeChange(size);
}
},
[onSizeChange]
);
useEffect(() => {
const notEqual = !sizeEqual(componentSize, previousSize);
if (notEqual) {
handleSizeChange({
current: componentSize,
previous: previousSize,
});
}
}, [componentSize, previousSize, handleSizeChange]);
return (
<div ref={wrapperRef} {...props}>
{children}
</div>
);
};
export const CustomSizedComponent = () => {
const [value, setValue] = useState({});
console.log("value:", value);
return (
<div class="flex flex-col border-gray-400 border-2 p-2 m-5">
<CustomSizeWrapper
class="text-xl border-secondary-300 border-2 p-5"
onSizeChange={(size) => setValue(size)}
>
{"This is some example text"}
</CustomSizeWrapper>
<pre>{`${JSON.stringify(value, null, 2)}`}</pre>
</div>
);
};