🌅 useViewport()
useViewport() provides a hook with the current window size and convenient functions to help building responsive apps.
Usage
Add it to your project:
yarn add use-viewport
Use it in your React app:
// App.js import React from 'react'import ViewportProvider useViewport from 'use-viewport' { return <ViewportProvider> <h1>useViewport</h1> <ViewportSize /> </ViewportProvider> } { const width height within below above = return <div> && <div>small</div> && <div>medium</div> && <div>large</div> <p> Current screen width is widthpx and the height is heightpx </p> </div> }
API
<ViewportProvider />
This is the provider component. It should be placed above any component using useViewport()
.
useViewport()
This is the hook to be used throughout the app.
It takes no parameters and returns the following:
width
: The current screen width.height
: The current screen height.within(min, max)
: A function that returnstrue
if the viewport width is betweenmin
andmax
.min
andmax
can be any number, or one of the available breakpoints. If -1 is passed as min or max, there will be no minimum or maximum.above(x)
: Returnstrue
if the viewport width is abovex
,false
otherwise.below(x)
: Returnstrue
if the viewport width is belowx
,false
otherwise.breakpoints
: An object that contains the number values of the different recommended breakpoints. It can be useful to set these values in CSS, for example.