useWindowWidthBreakpoints
A React hook for using window width breakpoints.
I essentially wanted to duplicate the logic of Bootstrap's media-breakpoint
Sass mixins within my React code.
Installation
npm install use-window-width-breakpoints
# OR
yarn add use-window-width-breakpoints
Usage
After importing the hook...
import useWindowWidthBreakpoints from "use-window-width-breakpoints";
...call it from the top level of your React function.
const breakpoint = useWindowWidthBreakpoints({
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
});
The hook has one optional parameter: an object containing the set of window width breakpoints (in pixels) you wish to use. If this parameter is omitted, Bootstrap's default breakpoints will be used. If you choose to specify your own set of breakpoints, sm
and lg
breakpoints are required, while xs
, md
, and xl
breakpoints are optional.
This hook returns an object containing the boolean results of several media queries. For example, if the width of the window is 800px
, the value of breakpoint
(as defined above) will be
{
xs: false,
sm: false,
md: true,
lg: false,
xl: false,
only: {
xs: false,
sm: false,
md: true,
lg: false,
xl: false,
},
up: {
xs: true,
sm: true,
md: true,
lg: false,
xl: false,
},
down: {
xs: false,
sm: false,
md: true,
lg: true,
xl: true,
},
between: {
xs: {
sm: false,
md: true,
lg: true,
xl: true,
},
sm: {
md: true,
lg: true,
xl: true,
},
md: {
lg: true,
xl: true,
},
lg: {
xl: false,
},
},
}
What's that good for? Say you have a React component you only want to display on md
-sized screens. Throw this into your JSX:
{breakpoint.md && <MyComponent />}
{/* OR */}
{breakpoint.only.md && <MyComponent />}
Or maybe you want to use one component on larger screens and a different one on smaller screens:
{breakpoint.up.lg ? <LargerVersion /> : <SmallerVersion />}
Or maybe you want to describe the size of the window in paragraph form with an odd sort of precision:
<p>
This window is {breakpoint.between.sm.lg ? "" : "pretty "}
{breakpoint.down.sm ? "small" : breakpoint.up.lg ? "big" : "average"}.
</p>
But that's up to you.
Have fun!
Contributing
If you'd like to contribute to this project (which would be awesome), the easiest way to set it up would be to install the GitHub CLI and then run the following:
gh repo fork tywmick/use-window-width-breakpoints --clone=true
cd use-window-width-breakpoints
npm install
Now, you can build the package with npm run build
, build and watch for changes with npm run dev
(automatically rebuilding on each change in the source), run the test suite with npm run test
, and create pull requests with gh pr create
.
After building the package, you can test it in another project on your machine by adding the local path as a dependency (e.g., by running npm install /path/to/local/use-window-width-breakpoints
in that other project).