react-viewport-height
A React hook that returns the size of one vh unit, 1% of the browser's inner window height, and keeps it up to date when the window resizes.
The package is maintained, but for new code, prefer the standard alternatives:
- To size elements, use the CSS
dvh,svh, andlvhunits. They follow the actual viewport height on mobile browsers and are widely supported. Read more about the new units. - To use the height in JavaScript, use
useWindowSizefrom usehooks-ts or react-use. Both return the window's inner width and height, souseWindowSize().height / 100is the value thatuseVHreturns.
Usage
npm install react-viewport-height
import useVH from 'react-viewport-height';
const ROW_HEIGHT = 40;
const Rows = ({ items }) => {
const vh = useVH();
const rowsThatFit = Math.floor((100 * vh) / ROW_HEIGHT);
return (
<ul>
{items.slice(0, rowsThatFit).map((item) => (
<li key={item} style={{ height: ROW_HEIGHT }}>
{item}
</li>
))}
</ul>
);
};
Read the documentation for more details. You can also play with a demo.