react-viewport-height

A utility for React to set 100vh equal to the actual browser inner window height.

Since vh has troubles on mobile browsers (primarily because of the address bar), there are several tricks to fix it.

Installing

  • npm:
npm install react-viewport-height
Shell
  • yarn:
yarn add react-viewport-height
Shell

This package works only in versions of React that support hooks.

Usage

useVH, a hook that you import from a package, adds a CSS custom property --vh with the value of 1% of window.innerHeight and returns it from the hook. If the window is resized, the hook updates --vh and vh.

There are 2 ways of setting an element's height. You can set it in css:

// index.js
import useVH from 'react-viewport-height';
import './index.css';

const App = () => {
  useVH();

  return <div className="app" />;
};
React JSX
/* index.css */
.app {
  min-height: calc(var(--vh, 1vh) * 100);
}
CSS

Otherwise, you can set height in a component directly:

import useVH from 'react-viewport-height';

const App = () => {
  const vh = useVH();

  return <div style={{ height: `${100 * vh}px` }} />;
};
React JSX

An important note: If you decide to stick to the first way, you should know that if a component with the hook gets unmounted, --vh gets removed.

GitHub

https://github.com/dimazuien/react-viewport-height