aragon / use-viewport

🌅 useViewport() · Viewport sizes and helper functions for responsive applications, quick and easy.
MIT License
12 stars 1 forks source link

🌅 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'

function App() {
  return (
    <ViewportProvider>
      <h1>useViewport</h1>
      <ViewportSize />
    </ViewportProvider>
  )
}

function ViewportSize() {
  const { width, height, within, below, above } = useViewport()

  return (
    <div>
      {below('medium') && <div>small</div>}
      {within('medium', 'large') && <div>medium</div>}
      {above('large') && <div>large</div>}
      <p>
        Current screen width is {width}px and the height is {height}px
      </p>
    </div>
  )
}

export default App

API

<ViewportProvider />

This is the provider component. It should be placed above any component using useViewport().

Apart from children it accepts the following props:

throttle

The interval in ms for window updates. Defaults to 100.

useViewport()

This is the hook to be used throughout the app.

It takes no parameters and returns the following: