react-match-width
A react utility (in the form of a higher order component) that makes it easy use the width media query allowing a higher degree of flexibility than CSS Media Queries
Installation
yarn add react-match-width
or
npm install react-match-width --save
Features
Basic usage
; { return <div> isBig: thispropsisBig ? 'yes' : 'no' <br /> isMedium: thispropsisMedium ? 'yes' : 'no' <br /> isSmall: thispropsisSmall ? 'yes' : 'no' <br /> </div> ; } isBig: minWidth: '700px' isMedium: minWidth: '420px' maxWidth: '700px' isSmall: maxWidth: '420px' MyComp;
Setting global defaults
When rendering on the server, there is no window
to query so we need to set some defaults in order to have an answer. This can be achieved by wrapping this component
// helpers/match-width-with-defaults.js; // produce a default enabled version of the moduleconst matchWidth = ; // app.js// ... use it as usual
Setting local defaults
Each use of the higher order component can specify the defaults for that use, just add a second parameter to the HOC call
//... define your component MyComp then wrap it: isBig: minWidth: '700px' isMedium: minWidth: '420px' maxWidth: '700px' isSmall: maxWidth: '420px' width: '500px'MyComp;
The matched API
; { return <div>Some comp</div>;} const ForNotSmall = ; { return <div> Render for not-small: <ForNotSmall /> </div> ; }
The renderIf API
; const IfSmall = ; { return <div> Will render if small: <IfSmall> This is small </IfSmall> </div> ; }
Future
Because this is a higher order component, it's config --the queries themselves-- is defined statically, maybe find a way of defining them dynamically
Credits
It uses matchmedia, a wrapper over matchMedia API that also supports server rendering
Related projects
- https://github.com/viruschidai/react-match-media - supports only the
matched
API style - https://github.com/contra/react-responsive - similar project but does not expose a HoC
- https://github.com/paulirish/matchMedia.js/ - polifill
- https://github.com/weblinc/media-match - another polifill
TODOs:
- pass in the defaults at runtime (dev purposes, no dynamic)
- maybe add a defaults provider
- support local default also for non hoc apis
- tests
- types
- CI
- document node and browser compatibility