Sometimes, just knowing the window width isn't enough. Sometimes you want to know if the window's orientation is portrait or landscape. Good thing you found this React hook.
npm install use-window-orientation# ORyarn add use-window-orientation
After importing the hook...
...call it from the top level of your React function.
const orientation portrait landscape = ;
This hook returns an object with three properties, each describing the current orientation of the window in a different way.
orientationwill be either
portraitwill be either
landscapewill be either
The easiest way to access these properties is by using object destructuring, as in the above example. One advantage of this method is that you only have to declare variables for the properties you actually want to use. Only plan on using the
portrait boolean in your code? Then just call the hook like this:
const portrait = ;
What's this hook good for? Say you have two components,
Explanation. You want
Explanation to come first if the window is portrait, but you want
Chart to come first if the window is landscape. Then arrange them in your JSX like this:
portrait && <Explanation /><Chart />landscape && <Explanation />
Or say you want to creep out your users by divining the orientation of their window:
<p>Well your window is orientation right now so you leave me no choice</p>
The possibilities are endless.
This hook has one optional parameter: an options object. There is currently only one option,
defaultOrientation, the default orientation you'd like to return if no window exists (such as if a search engine is crawling your page). Valid
"landscape", and if you omit the option, it will default to
const orientation portrait landscape =;
This hook only deals with the window orientation, not the device orientation. It calculates this orientation using
window.innerHeight. It does not consult
window.orientation at all because that feature has been deprecated.
Also, in the rare case that the window's width and height are equal, useWindowOrientation will just report the orientation as portrait.
If you'd like to contribute to this project (which would be awesome), here's how to set it up:
Fork this repository to your own GitHub account.
Clone it to your device.git clone https://github.com/YOUR_USERNAME/use-window-orientation.git
Add this repository as a remote, so you can pull upstream changes in the future with
git pull upstream master.cd use-window-orientationgit remote add upstream https://github.com/tywmick/use-window-orientation.git
Install dependencies.npm install
Now, you can build the package with
npm run build, build and watch for changes with
npm run dev (automatically rebuilding on each change in the source), and run the test suite with
npm run test.
After building the package, you can test it in another project on your machine by adding the local path as a dependency (e.g., by running
npm install /path/to/local/use-window-orientation in that other project).