Simple matchMedia based React component to conditionally render components based on breakpoints.
- ✅ No dependencies
- ✅ Small profile (4kb)
- ✅ Flexible API
- ✅ Customizable breakpoints
yarn add react-media-breakpoints
or
npm install --save react-media-breakpoints
To use the pre-configured Breakpoints, just import and use the component. It will re-render when the matchMedia listener matches the new breakpoint.
//Import component
import Breakpoint from 'react-media-breakpoints'
...
//Use component based on breakpoints
<Breakpoint
desktop={() => (/* Render on desktop */)}
tablet={() => (/* Render on tablet */)}
mobile={() => (/* Render on mobile) */)}
/>
//It can also be used more generically with a render prop...
<Breakpoint
render={(breakpoint) => (/* Conditionally render based on the render prop. Called with desktop, tablet, mobile */)}
/>
//...Or as a child function
<Breakpoint>
{breakpoint => (/* Conditionally render here too :) */)}
</Breakpoint>
By default, the pre-configuration is as follows:
name | minWidth | maxWidth |
---|---|---|
mobile | none | 767px |
tablet | 768px | 1023px |
desktop | 1024px | none |
Breakpoints can also be configured app wide by importing the configure method at the top of your App.js(x)
//App.js
import { configure } from 'react-media-breakpoints';
configure([{
name: 'customBp1',
minWidth: 1000,
maxWidth: 1100
}, {
name: 'customBp2',
minWidth: 1101
}, {
name: 'customBp3',
maxWidth: 999
}]);
//Elsewhere in your app
<Breakpoint
customBp1={() => (/* bp1 */)}
customBp2={() => (/* bp2 */)}
customBp3={() => (/* bp3 */)}
/>
<Breakpoint
render={(breakpoint) => (/* called with customBp1, customBp2, customBp3 etc. */)}
/>
Note that configurations are shared across the app - it is advised to set up once and re-use these configurations across the app.
Breakpoints can be used once off with a query for just the component instance. In this case, it will not use the configured breakpoints.
import Breakpoint from 'react-media-breakpoints';
<Breakpoint
query="(min-width: 600px) and (max-width: 1200px)"
render={() => { /* Called if custom query is resolved */ }}
/>
<Breakpoint query="(min-width: 600px) and (max-width: 1200px)">
{ () => { /* Called if custom query is resolved */ }}
</Breakpoint>
Using this package in a server context will result in a default breakpoint, server
, to be rendered. This allows you to specify the most expensive breakpoint to pre-render (e.g. the most amount of API calls).
//On a server
import Breakpoint from 'react-media-breakpoints';
import MyCoolServerComponent from './Component';
<Breakpoint server={() => { /* Render a component here */ }} />
<Breakpoint server={MyCoolServerComponent} />
Custom config overlaps/misses pixel ranges
In this scenario, Breakpoint
will not call any render method - this is largely do to directly translating the config to media queries.