react-matchmedia-connect
- Higher order components for the matchMedia API
- Receive props that indicate whether your media queries match
Installation
npm install react-matchmedia-connect --save
Usage
createMatchMediaConnect
createMatchMediaConnect
lets you register a set of media queries. If one of the queries changes, you component will be updated.
; // Define some media queries and give them a keyconst connect = ;
Then use this connect function throughout your app:
const Component = <div> <div>isLandscape ? 'landscape' : 'portrait'</div> <div>isMin400 ? 'at least 400' : 'less than 400'</div> </div>;// This component only needs `isLandscape` and `isMin400`const ConnectedComponent = Component;
const OtherComponent = isTablet ? <div>Tablet</div> : <div>No tablet</div>;// This component only needs `isTablet`const OtherConnectedComponent = Component;
createResponsiveConnect
createResponsiveConnect
expects a list of breakpoints and creates the respective media queries with createMatchMediaConnect
. You'll get a isMin<Size>
and isMax<Size>
property for each breakpoint as well as a isPortrait
and isLandscape
property.
;const connect = ;
const Component = <div> <div>isMinMd ? 'greater than 992px' : 'less than 992px'</div> <div>isMaxMd ? 'less than 1200px' : 'greater than 1199px'</div> <div>isMinMd && isMaxMd ? 'between 992px and 1199px' : 'other'</div> </div>;// Only connect to `isMinMd` and `isMaxMd`const ConnectedComponent = Component;
API
createMatchMediaConnect(mediaQueries)
mediaQueries
(Object): A set of media queries.returns
(Function): connect function that connects your components to changes
const connect = ;
connect(properties)
properties
(Array): An array of properties that your component should receivereturns
(Function): wrapWithConnect higher order function
const wrapWithConnect = ;
wrapWithConnect(Component)
Component
(Component): The component that you want to connectreturns
(Component): Connected component
const Component = <div>isMin400 ? 'at least 400' : 'less than 400'</div>;// This component only needs `isLandscape` and `isMin400`const ConnectedComponent = ;
createResponsiveConnect(breakpoints)
breakpoints
(Object): A set of breakpointsreturns
(Function): connect function that connects your components to changes
Default breakpoints:
const defaultBreakpoints = xs: 480 sm: 768 md: 992 lg: 1200;
Examples
Run the simple example:
# Make sure that you've installed the dependencies npm install# Move to example directory cd react-matchmedia-connect/examples/simplenpm installnpm start
Tests
# Make sure that you've installed the dependencies npm install# Run tests npm test
Code Coverage
# Run code coverage. Results can be found in `./coverage` npm run test:cov
License
MIT