responsive-jsx
Higher-order React components for responsive JSX.
Getting Started
Install with npm.
$ npm install responsive-jsx --save
Once responsive-jsx is installed, import the library in your React projects.
;
API
responsive-jsx comes with a higher-order component, and other functions for global configuration.
Responsive
The Responsive component is a simple wrapper for your JSX that renders its children only if the given media query matches. If the query is invalid, its children will always be returned. Responsive takes a breakpoint name and a query type, or a css media query.
; const MyComponent = { return <Fragment> <Responsive small up> You can see me on windows larger than small </Responsive> <Responsive medium only> You can see me only when window is exactly medium </Responsive> <Responsive large down> You can see me when window is smaller than large </Responsive> <Responsive query='(min-width: 320px)'> You can see me on windows at least as large as mobile </Responsive> </Fragment> ;};
A breakpoint is one of small, medium, and large, or any of the breakpoints set by user. Type is one of up, down, and only. The query prop takes in a css media query.
Note: In case of multiple breakpoints or types, the first in the order above is prioritized, and if both css query and custom breakpoint are defined, the css query takes priority.
Callback Function
The Responsive component will pass in a boolean value if a callback function is passed in as its children for cases where your application needs to handle unmatched query differently.
; const MyComponent = { return <Fragment> <Responsive small up> { return match ? 'Hello' : 'Goodbye'; } </Responsive> </Fragment> ;};
setBreakpoints
setBreakpoints is a function that lets you set your custom breakpoints globally.
; ; const MyComponent = { return <Responsive mobile up> You can see me on windows larger than mobile </Responsive> ;};
It takes an object of breakpoint name to its width in pixels. Setting your custom breakpoints allows you to use them anywhere in your app. Define your breakpoints in the entry point of your React app.
useQuery
useQuery is a custom hook in case you need to handle responsiveness programmatically in Javascript.
; const MyComponent = { const match = ; return match && 'You can only see me on windows smaller than 720px';};
The hook takes in a css query as a string and returns a local state boolean which updates according to adjustments in the window size.
breakpoints
breakpoints is a variable for the currently defined breakpoints of the app.
Built With
responsive-jsx is built with React 16.8, which introduced hooks.
Libraries used:
Author
Gino Jacob - Github
Feedback is very much welcomed.
License
This project is licensed under the MIT License - see the LICENSE.md file for details