react-match-media-context

1.0.8 • Public • Published

react-match-media-context

✨ Super lightweight package to handle responsive as needed with React context and window.matchMedia!

giphy

Installation

$ npm install react-match-media-context  
$ yarn add react-match-media-context  

How to use?!

  1. Import the context and put on ROOT component and apply with your custom configuration to media prop!
// App.js
 
import { MatchMediaProvider } from 'react-match-media-context'
 
// custom configuration example
// you can get { mobile, tablet, desktop, customScreen, foo, bar, ...whatever you need } from context!
 
const media = {
  bar: {
    minWidth: '250px',
    maxWidth: '450px',
  },
  mobile: {
    maxWidth: '450px',
    isDefaultValue: true, // fallback state on ssr
  },
  tablet: {
    minWidth: '451px',
    maxWidth: '800px',
  },
  desktop: {
    minWidth: '801px',
    maxWidth: '1000px',
  },
  foo: {
    minWidth: '1000px',
  },
  [your custom variable name]: { 
    minWidth: 'xxx',
    maxWidth: 'xxx', 
    isDefaultValue: true, // optional
  }
}
 
const App = () => {
  return (
    <MatchMediaProvider media={media}>
      <HomePage />
    </MatchMediaProvider>
  )
}
  1. Go to your responsive styled component
// NavigationBar.js
 
import React, { useContext } from 'react'
import MatchMediaContext from 'react-match-media-context'
 
import NavMobile from './nav/mobile'
import NavDesktop from './nav/desktop'
 
const NavigationBar = () => {
  // relate to above configuration, you can get;
  // { mobile, tablet, desktop, foo, bar } = useContext(MatchMediaContext)
  const { mobile } = useContext(MatchMediaContext)
  const navBarComponent = mobile ? NavMobile : NavDesktop
 
  return (
    <div className="some-navbar-classname">
       {navBarComponent}
    </div>
  )
}

Limitation!

Props

MatchMediaProvider's props

  • media <{ [key: string]: Object }>
    • Object.minWidth <string>: minimum screen width to be matched
    • Object.maxWidth <string>: maximum screen width to be matched
    • Object.isDefaultValue? <boolean>: if it's defined as true, when we cannot access window.matchMedia (SSR) or the current running browser is not supported. The value of this key will be true.

Dependencies (0)

    Dev Dependencies (12)

    Package Sidebar

    Install

    npm i react-match-media-context

    Weekly Downloads

    1

    Version

    1.0.8

    License

    MIT

    Unpacked Size

    11.9 kB

    Total Files

    10

    Last publish

    Collaborators

    • anchvy