Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

use-match-media-hook

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-match-media-hook

useMatchMedia react hook for responsive components.

  • 1.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
6.9K
increased by4.32%
Maintainers
1
Weekly downloads
 
Created
Source

use-match-media

useMatchMedia react hook for responsive components.

There are cases that is needed to set conditions outside the render/return of the component. For that another way to set a condition depending on the media query, is using a hook.

Installation

  1. Install yarn add use-match-media-hook or npm i --save use-match-media-hook

Arguments

  • queries : array of media queries following the spec.
  • defaultValues : default values in case you want to control SSR default value, defaults to false

Usage

Common usage:
import useMatchMedia from 'use-match-media-hook'

const queries = [
  '(max-width: 400px)',
  '(min-width: 800px)'
]

const Component = () => {
  const [mobile, desktop] = useMatchMedia(queries)

  if(mobile) return <MobileComponent />

  return desktop ? <ComponentOne /> : <ComponentTwo />
}
Desktop first strategy

The following example will render true in the server (if window doesn't exists).

import useMatchMedia from 'use-match-media-hook'

const queries = [
  '(min-width: 600px)'
]

const Component = () => {
  const [desktop] = useMatchMedia(queries)

  return desktop ? <ComponentOne /> : <ComponentTwo />
}

Server side compatible

Since there is not a reliable-simple way to know the client window, the library doesn't make any assuptions, but it lets you decide which is your SSR strategy.

The second argument is the initial value that is used in the SSR, so depending of the strategy you might want to set it as false or true.

import useMatchMedia from 'use-match-media-hook'

const queries = [
  '(min-width: 600px)'
]

const Component = () => {
  const [desktop] = useMatchMedia(queries, [true]) // it receives a second argument with the SSR value, false by default

  return desktop ? <ComponentOne /> : <ComponentTwo />
}

FAQs

Package last updated on 16 Oct 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc