0.3.1 • Published 2 years ago

media-hooks v0.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Media Hooks CI/CD

Table of Content

Installation:

You can install using:

yarn add media-hooks

// or

npm install media-hooks

How to use:

Media hooks provides two ways to use.

First way:

Use provider with patterns. Current support one operator (AND | OR).

App.js

import MediaProvider from 'media-hooks';

const App = () => {
  const patterns = {
    mobile: '(max-width: 768px)', // or { minWidth: 768 }
    tablet: '(min-width: 769px) and (max-width: 1023px)', // or { minWidth: 769, operator: 'and', maxWidth: 1023 }
    desktop: '(min-width: 1024px)' // or { maxWidth: 1024 }
  }
  
  return (
    <MediaProvider patterns={patterns}>
      <Component />
    </MediaProvider>
  );
}

export default App;

Component.js

import { useMedia } from 'media-hooks';

const Component = () => {
  const isMobile = useMedia('mobile');
  const isTablet = useMedia('tablet');
  const isDesktop = useMedia('desktop');
  
  return (
    <>
      {isMobile && <MobileComponent />}
      {isTablet && <TabletComponent />}
      {isDesktop && <DesktopComponent />}
    </>
  );
}

export default Component;

Second way:

Use custom CSS Media Query.

Component.js

import { useCustomMedia } from 'media-hooks';

const Component = () => {
  const isMobile = useCustomMedia('(max-width: 768px)');
  const isTablet = useCustomMedia('(min-width: 769px) and (max-width: 1023px)');
  const isDesktop = useCustomMedia('(min-width: 1024px)');
  
  return (
    <>
      {isMobile && <MobileComponent />}
      {isTablet && <TabletComponent />}
      {isDesktop && <DesktopComponent />}
    </>
  );
}

export default Component;

Definition:

<MediaProvider />

PropDescriptionExample
patternsobject patterns.<MediaProvider patterns={{ mobile: '(min-width: 768px)' }}>...</MediaProvider>
patternsobject patterns.<MediaProvider patterns={{ mobile: { minWidth: 768 } }}>...</MediaProvider>

useMedia()

ParamDescriptionExample
patternstring pattern key in patterns.const isMobile = useMedia('mobile')
configobject configuration objectconst isMobile = useMedia('mobile', { default: true })
config.defaultbool fallback used when Media API is unavailableconst isMobile = useMedia('mobile', { default: true })

useCustomMedia()

ParamDescriptionExample
querystring CSS Media Query.const isMobile = useCustomMedia('max-width: 768px')
configobject configuration objectconst isMobile = useCustomMedia('max-width: 768px', { default: true })
config.defaultbool fallback used when Media API is unavailableconst isMobile = useCustomMedia('max-width: 768px', { default: true })

P.S: If Media API is unavailable and default value is not provided the hooks will return undefined;


MIT License

Copyright (c) 2021 Matheus Pelegrinetti

0.3.1

2 years ago

0.3.0

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago