@ryvora/react-use-size
v2.0.0
Published
📐✨ Get the width and height of a DOM element in React. Lightweight and efficient!
Downloads
10
Maintainers
Readme
use-size 📐✨
Hello, Dimension Detective! 🕵️♂️
The use-size hook is a specialized hook, often simpler than use-rect, focused specifically on getting the width and height of a DOM element. It usually employs a ResizeObserver to efficiently update these dimensions whenever the element resizes.
It's like having a dedicated width and height sensor for your HTML elements! 📏↔️↕️
Why use-size?
- Performance: If you only need width and height,
use-sizecan be more lightweight than a fulluse-rectwhich might track position too. - Simplicity: A more focused API for a common use case.
- Responsive Components: Easily make components adapt to their own size rather than just the viewport.
Basic Usage:
import { useSize } from '@ryvora/react-use-size'; // Hook name might vary
import React, { useRef } from 'react';
function MyResponsiveBox() {
const boxRef = useRef<HTMLDivElement>(null);
const size = useSize(boxRef);
return (
<div>
<div
ref={boxRef}
style={{
width: '75%',
minHeight: '100px',
border: '2px solid green',
padding: '10px',
resize: 'horizontal', // Make it resizable for demo
overflow: 'auto',
}}
>
Try resizing me horizontally!
{size && (
<p>
Current Width: {size.width}px, Current Height: {size.height}px
</p>
)}
{size && size.width < 300 && <p style={{ color: 'red' }}>I'm getting pretty small!</p>}
</div>
</div>
);
}Know the dimensions, rule the layout! 👑🖼️
