Package Exports
- react-responsiveness
Readme
React Responsiveness
I wanted something really easy to use, light as a feather.
To be fair, I am a bit obsessed with both performance and ease of use. If curios, scroll down to How it works.
Installation
yarn
yarn add react-responsivenessnpm
npm i react-responsivenessDemo
Usage
A) Add provider
import { ResponsivenessProvider, Presets } from "react-responsiveness";
function App() {
// ...
}
const WithResponsiveness = () => (
<ResponsivenessProvider breakpoints={Presets.Bootstrap_5}>
<App />
</ResponsivenessProvider>
);
export default WithResponsiveness;Note: Default breakpoints value is already set to Bootstrap 5's responsiveness breakpoints preset:
Presets.Bootstrap_5 = {
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
xxl: 1400,
};B) Inside provider:
import { useResponsiveness } from "react-responsiveness";
const { isMin, isMax, isOnly, currentInterval } = useResponsiveness()
return (<>
<div>Current interval {currentInterval}</div>
{isMin('md') && (
// @media (min-width: 768px)
<div>content...</div>
)}
{isMax('md') && (
// @media (max-width: 991.9px)
<div>content...</div>
)}
{isOnly('md') && (
// @media (min-width: 768px) and (max-width: 991.9px)
<div>content...</div>
)}
</>)Available presets:
Bootstrap_3, Bootstrap_4, Bootstrap_5, Bulma, Chakra, Foundation, Ionic, Material_Design, Materialize, Material_UI, Quasar, Semantic_UI, Skeleton, Tailwind_CSS, Windi_CSS
Notes:
- If you maintain a CSS framework (or use one often) and want its preset added, open an issue or a PR.
- If you spot any inaccuracy in presets (either typo or due to library update), please, let me know, I'll correct it.
Bespoke intervals:
<ResponsivenessProvider
breakpoints={{
small: 0,
medium: 777,
large: 1234,
}}
>
// ...
</ResponsivenessProvider>import { useResponsiveness } from "react-responsiveness";
const { isOnly } = useResponsiveness()
return (<>
{isOnly('medium') && (
// @media (min-width: 777px) and (max-width: 1233.9px)
<div>content...</div>
)}
</>)How it works:
- uses the native
window.matchMedia(queryString)and only reacts to changes in the query'smatchesvalue. It's the same API powering CSS media queries - listeners are placed on the
MediaQueryListinstances, meaning they are garbage collected as soon as the app is unmounted, without leaving bound events behind on<body>orwindowobject - no global pollution
- in terms of memory and/or CPU consumption, listening to
window.matchMadia'change' events is a few hundred times lighter than using the "traditional"resizeevent listener method