├── .gitignore ├── README.md ├── index.js ├── package.json └── test └── main.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .DS_Store 3 | compiled.js 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # React Native Media Queries 4 | 5 | This module brings media queries like functionality to React Native styles. 6 | Uses `React.Dimensions.get('window')` (or the `nativeEvent` data when bound to `onLayout`) 7 | to determine width and height of the screen. 8 | 9 | 10 | ### Install 11 | 12 | `npm install react-native-media-queries` 13 | 14 | 15 | ### Quick Start 16 | 17 | If you want to write this: 18 | 19 | ```css 20 | /* This is of course CSS, don't paste it in your RN app, you fool! */ 21 | .logo { 22 | height: 200px; 23 | } 24 | 25 | @media (max-height: 500px) { 26 | .logo { 27 | height: 120px; 28 | } 29 | } 30 | ``` 31 | 32 | Write this instead: 33 | 34 | ```javascript 35 | import { createStyles, maxHeight } from 'react-native-media-queries'; 36 | 37 | // Define your styles 38 | const base = { 39 | logo: { 40 | height: 200 41 | } 42 | }; 43 | 44 | const styles = createStyles( 45 | base, 46 | 47 | // override styles only if screen height is less than 500 48 | maxHeight(500, { 49 | logo: { 50 | height: 120 51 | } 52 | }) 53 | ); 54 | 55 | ``` 56 | 57 | Then use `styles` in your components as you're already used to, i.e. ``. 58 | 59 | 60 | ### API 61 | 62 | #### maxHeight(height, styles) 63 | Equivalent to `max-height` in CSS. 64 | Apply `styles` only if screen height is less than or equal `height`. 65 | 66 | #### minHeight(height, styles) 67 | Equivalent to `min-height` in CSS. 68 | Apply `styles` only if screen height is greater than or equal `height`. 69 | 70 | #### maxWidth(width, styles) 71 | Equivalent to `max-width` in CSS. 72 | Apply `styles` only if screen width is less than or equal `width`. 73 | 74 | #### minWidth(width, styles) 75 | Equivalent to `min-width` in CSS. 76 | Apply `styles` only if screen width is greater than or equal `width`. 77 | 78 | #### aspectRatio(ratio, styles) 79 | Equivalent to `aspect-ratio` in CSS. 80 | Apply `styles` only if the aspect ratio of the screen is the same as the ratio provided. 81 | *Note*: Ratio must be in the form `16/9`. 82 | 83 | #### maxAspectRatio(ratio, styles) 84 | Equivalent to `max-aspect-ratio` in CSS. 85 | Apply `styles` only if the aspect ratio of the screen is less or equal than the ratio provided. 86 | 87 | #### minAspectRatio(ratio, styles) 88 | Equivalent to `min-aspect-ratio` in CSS. 89 | Apply `styles` only if the aspect ratio of the screen is greater or equal than the ratio provided. 90 | 91 | #### `createStyles(baseStyles, expression1, expression2...)` 92 | Start from `baseStyles` and apply further matching expressions. 93 | 94 | 95 | 96 | ### Compose expressions 97 | Expressions are composable meaning you can apply a certain style only 98 | if the screen height is greater than X AND less than Y (for example). 99 | 100 | Basically, if you want something like this 101 | `@media (min-height: 500px) and (max-height: 1200px)`, 102 | you'd write this instead: 103 | 104 | ```javascript 105 | const base = { 106 | logo: { 107 | height: 200 108 | } 109 | }; 110 | 111 | const styles = createStyles( 112 | base, 113 | 114 | // override styles only if screen height is greater than 500 and less than 1300 115 | minHeight(500, maxHeight(1300, { 116 | logo: { 117 | height: 120 118 | } 119 | })) 120 | ); 121 | 122 | ``` 123 | 124 | 125 | And you can have multiple expressions too: 126 | 127 | ```javascript 128 | const base = { 129 | logo: { 130 | height: 200 131 | } 132 | }; 133 | 134 | const exp1 = { 135 | logo: { 136 | borderWidth: 5 137 | } 138 | }; 139 | 140 | const exp2 = { 141 | logo: { 142 | backgroundColor: '#ddd' 143 | } 144 | }; 145 | 146 | 147 | const styles = createStyles( 148 | base, 149 | minHeight(500, exp1), 150 | minWidth(750, exp2) 151 | ); 152 | ``` 153 | 154 | 155 | 156 | ### React (ahahah :/) to screen orientation changes / window resize 157 | 158 | As of version `0.1.0` it is possible to update styles whenever the dimensions of the screen change, 159 | achieving a closer media queries implementation to what is available with CSS on the web. 160 | 161 | A function `onLayout` is provided in the object returned from `createStyles()` (eg. `styles.onLayout`). 162 | You will need to call this function everytime your root component updates its layout, so you'll have to 163 | bind it to the component's `onLayout` prop. 164 | 165 | 166 | 167 | ```javascript 168 | 169 | class MyComponent { 170 | render() { 171 | return ( 172 | 173 | YO mama 174 | 175 | ); 176 | } 177 | } 178 | 179 | const base = { 180 | title: { 181 | fontSize: 16 182 | } 183 | }; 184 | 185 | const biggerFont = { 186 | title: { 187 | fontSize: 20, 188 | backgroundColor: 20, 189 | } 190 | }; 191 | 192 | 193 | const styles = createStyles( 194 | base, 195 | minHeight(500, biggerFont), 196 | ); 197 | 198 | ``` 199 | 200 | **NOTE:** This example, as is, **will not work** because React does not re render the interface unless 201 | the state or the props have been updated. You can force a component to re render (even if it's not encouraged), 202 | so that this module actually works. It's a bit of a hack but depending on your situation it might be the only 203 | way to have the styles update on orientation changes / window resize. You can pass a callback to `onLayout`, 204 | it will get fired only if the styles have changed. 205 | 206 | Here's how you would use `forceUpdate` to force a re render and make the previous example work: 207 | 208 | ```javascript 209 | 210 | class MyComponent { 211 | render() { 212 | return ( 213 | this.forceUpdate())}> 214 | YO mama 215 | 216 | ); 217 | } 218 | } 219 | 220 | const base = { 221 | title: { 222 | fontSize: 16 223 | } 224 | }; 225 | 226 | const biggerFont = { 227 | title: { 228 | fontSize: 20, 229 | backgroundColor: 20, 230 | } 231 | }; 232 | 233 | 234 | const styles = createStyles( 235 | base, 236 | minHeight(500, biggerFont), 237 | ); 238 | 239 | ``` 240 | 241 | 242 | 243 | ### Changelog 244 | 245 | #### 0.3.0 246 | Introduce `aspectRatio` queries. 247 | 248 | #### 0.1.0 249 | Introduce `onLayout` callback and reactive updates to window size changes. 250 | Thanks to [Quincy Mitchell](http://twitter.com/quincymitch) for providing feedback and testing on Windows :) 251 | 252 | 253 | 254 | ### License 255 | 256 | 257 | > Copyright (c) 2016, Marco Sampellegrini 258 | 259 | 260 | > Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. 261 | 262 | > THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 263 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Copyright (c) 2016, Marco Sampellegrini 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee 6 | is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. 7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE 8 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE 9 | FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 10 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, 11 | ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 12 | */ 13 | 14 | 15 | const Dimensions = require('react-native').Dimensions; 16 | 17 | 18 | const computeStyles = (dimensions, base, ...extra) => { 19 | return extra.reduce((acc, fn) => { 20 | const properties = fn(dimensions); 21 | const merged = Object.keys(properties).reduce((s_acc, key) => 22 | ({ 23 | ...s_acc, 24 | [key]: {...base[key], ...properties[key]} 25 | }), {}); 26 | 27 | return { 28 | ...acc, 29 | ...merged 30 | }; 31 | 32 | }, base); 33 | }; 34 | 35 | 36 | const getStyles = base => { 37 | let styles = {}; 38 | let computed = {}; 39 | 40 | Object.keys(base).map(key => { 41 | Object.defineProperty(styles, key, { 42 | get: function () { 43 | return computed[key]; 44 | } 45 | }); 46 | }); 47 | 48 | const update = newStyles => { 49 | if (JSON.stringify(newStyles) === JSON.stringify(computed)) { 50 | return false; 51 | } 52 | 53 | computed = newStyles; 54 | return true; 55 | }; 56 | 57 | return { styles, update }; 58 | }; 59 | 60 | 61 | export const createStyles = (base, ...extra) => { 62 | const { styles, update } = getStyles(base); 63 | 64 | styles.onLayout = fn => event => { 65 | const dimensions = Dimensions.get('window'); 66 | const computed = computeStyles(dimensions, base, ...extra); 67 | const changed = update(computed); 68 | if (changed && fn) fn(); 69 | }; 70 | 71 | styles.onLayout()(); 72 | return styles; 73 | }; 74 | 75 | 76 | const createQueryFn = (test) => (target, styles) => (dimensions) => { 77 | if (!test(target, dimensions)) return {}; 78 | 79 | return typeof styles === 'function' ? styles(dimensions) : styles; 80 | }; 81 | 82 | export const maxHeight = createQueryFn((target, { height }) => target >= height); 83 | export const minHeight = createQueryFn((target, { height }) => target <= height); 84 | 85 | export const maxWidth = createQueryFn((target, { width }) => target >= width); 86 | export const minWidth = createQueryFn((target, { width }) => target <= width); 87 | 88 | 89 | const aspectRatioRound = value => value.toFixed(2); 90 | const aspectRatioQuery = fn => createQueryFn((target, { width, height }) => { 91 | return fn(aspectRatioRound(target), aspectRatioRound(width / height)); 92 | }); 93 | 94 | export const maxAspectRatio = aspectRatioQuery((target, aspectRatio) => target >= aspectRatio); 95 | export const minAspectRatio = aspectRatioQuery((target, aspectRatio) => target <= aspectRatio); 96 | export const aspectRatio = aspectRatioQuery((target, aspectRatio) => target == aspectRatio); 97 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-media-queries", 3 | "description": "Media queries like functionality for React Native", 4 | "author": "Marco Sampellegrini ", 5 | "version": "0.3.0", 6 | "main": "compiled.js", 7 | "scripts": { 8 | "prepublish": "npm run compile", 9 | "compile": "NODE_ENV=build ./node_modules/.bin/babel index.js -o compiled.js", 10 | "test": "NODE_ENV=build ./node_modules/.bin/mocha --compilers js:babel-core/register ./test" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/alpacaaa/react-native-media-queries" 15 | }, 16 | "license": "MIT", 17 | "devDependencies": { 18 | "babel": "^6.3.26", 19 | "babel-cli": "^6.9.0", 20 | "babel-core": "^6.4.0", 21 | "babel-preset-es2015": "^6.3.13", 22 | "babel-preset-stage-2": "^6.3.13", 23 | "chai": "^3.4.1", 24 | "mocha": "^2.3.4", 25 | "proxyquire": "^1.7.3" 26 | }, 27 | "babel": { 28 | "env": { 29 | "build": { 30 | "presets": [ 31 | "es2015", 32 | "stage-2" 33 | ] 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/main.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | const proxyquire = require('proxyquire'); 4 | const expect = require('chai').expect; 5 | 6 | 7 | const RNStub = { 8 | setDimensions(width, height) { 9 | RNStub.data = { width, height }; 10 | }, 11 | 12 | Dimensions: { 13 | get(){ return RNStub.data } 14 | }, 15 | 16 | '@noCallThru': true 17 | }; 18 | 19 | 20 | const testStyles = (actual, expected) => { 21 | Object.keys(expected).map(key => { 22 | expect(actual).to.have.property(key).and.deep.equal(expected[key]) 23 | }) 24 | }; 25 | 26 | 27 | const layoutUpdateTest = fn => { 28 | RNStub.setDimensions(300, 500); 29 | 30 | const base = { 31 | someclass: { 32 | color: 'blue' 33 | }, 34 | anotherclass: { 35 | color: 'green' 36 | } 37 | }; 38 | 39 | const extra = { 40 | anotherclass: { 41 | color: 'red' 42 | } 43 | }; 44 | 45 | 46 | const result = createStyles( 47 | base, 48 | minHeight(600, extra) 49 | ); 50 | 51 | testStyles(result, base); 52 | 53 | // update window size 54 | RNStub.setDimensions(300, 800); 55 | fn(result); 56 | 57 | testStyles(result, { 58 | ...base, 59 | ...extra 60 | }); 61 | 62 | return result; 63 | }; 64 | 65 | 66 | 67 | const Index = proxyquire('../index', { 'react-native': RNStub }); 68 | const { 69 | createStyles, 70 | maxHeight, 71 | minHeight, 72 | minAspectRatio, 73 | } = Index; 74 | 75 | 76 | 77 | describe('createStyles', () => { 78 | 79 | it('works with base styles only', () => { 80 | const base = { 81 | someclass: { 82 | color: 'blue' 83 | } 84 | }; 85 | 86 | testStyles(createStyles(base), base); 87 | }); 88 | 89 | 90 | it('extends base styles', () => { 91 | RNStub.setDimensions(300, 500); 92 | 93 | const base = { 94 | someclass: { 95 | color: 'blue' 96 | }, 97 | anotherclass: { 98 | color: 'green' 99 | } 100 | }; 101 | 102 | const extra = { 103 | anotherclass: { 104 | color: 'red' 105 | } 106 | }; 107 | 108 | const result = createStyles( 109 | base, 110 | maxHeight(600, extra) 111 | ); 112 | 113 | testStyles(result, { 114 | ...base, 115 | ...extra 116 | }); 117 | }); 118 | 119 | 120 | 121 | it('does not merge styles if query is unmet', () => { 122 | RNStub.setDimensions(300, 500); 123 | 124 | const base = { 125 | someclass: { 126 | color: 'blue' 127 | } 128 | }; 129 | 130 | const result = createStyles( 131 | base, 132 | maxHeight(200, { 133 | anotherclass: { 134 | color: 'red' 135 | } 136 | }) 137 | ); 138 | 139 | testStyles(result, base); 140 | }); 141 | 142 | 143 | 144 | it('merges properties when the same class is present', () => { 145 | RNStub.setDimensions(300, 500); 146 | 147 | const base = { 148 | someclass: { 149 | color: 'blue' 150 | }, 151 | anotherclass: { 152 | color: 'red' 153 | } 154 | }; 155 | 156 | const result = createStyles( 157 | base, 158 | maxHeight(600, { 159 | someclass: { 160 | fontSize: 12 161 | } 162 | }) 163 | ); 164 | 165 | testStyles(result, { 166 | someclass: { 167 | color: 'blue', 168 | fontSize: 12 169 | }, 170 | anotherclass: { 171 | color: 'red' 172 | } 173 | }); 174 | }); 175 | 176 | 177 | 178 | it('overrides properties on the same class', () => { 179 | RNStub.setDimensions(300, 500); 180 | 181 | const base = { 182 | someclass: { 183 | color: 'blue' 184 | } 185 | }; 186 | 187 | const result = createStyles( 188 | base, 189 | maxHeight(600, { 190 | someclass: { 191 | color: 'red' 192 | } 193 | }) 194 | ); 195 | 196 | testStyles(result, { 197 | someclass: { 198 | color: 'red' 199 | } 200 | }); 201 | }); 202 | 203 | 204 | it('computes valid queries and ignores invalid ones', () => { 205 | RNStub.setDimensions(300, 500); 206 | 207 | const base = { 208 | someclass: { 209 | color: 'blue' 210 | }, 211 | anotherclass: { 212 | color: 'green' 213 | } 214 | }; 215 | 216 | const invalid = { 217 | notpresent: { 218 | fontSize: 12 219 | } 220 | }; 221 | 222 | const valid = { 223 | anotherclass: { 224 | color: 'red' 225 | } 226 | }; 227 | 228 | 229 | const result = createStyles( 230 | base, 231 | minHeight(400, valid), 232 | maxHeight(200, invalid) 233 | ); 234 | 235 | testStyles(result, { 236 | ...base, 237 | ...valid 238 | }); 239 | }); 240 | 241 | 242 | 243 | it('allows queries composition (AND operand)', () => { 244 | RNStub.setDimensions(300, 500); 245 | 246 | const base = { 247 | someclass: { 248 | color: 'blue' 249 | }, 250 | anotherclass: { 251 | color: 'green' 252 | } 253 | }; 254 | 255 | const extra = { 256 | anotherclass: { 257 | color: 'red' 258 | } 259 | }; 260 | 261 | 262 | const result = createStyles( 263 | base, 264 | minHeight(400, maxHeight(600, extra)) 265 | ); 266 | 267 | testStyles(result, { 268 | ...base, 269 | ...extra 270 | }); 271 | }); 272 | 273 | 274 | it('updates styles when `onLayout` is triggered (native event not supplied)', () => { 275 | layoutUpdateTest(result => result.onLayout()()); 276 | }); 277 | 278 | it('updates styles when `onLayout` is triggered (with native event)', () => { 279 | layoutUpdateTest(result => result.onLayout()({ 280 | nativeEvent: { 281 | layout: { width: 300, height: 800 } 282 | } 283 | })); 284 | }); 285 | 286 | it('correctly fires the supplied callback when styles update', () => { 287 | let called = 0; 288 | const callback = () => called++; 289 | const styles = layoutUpdateTest(result => result.onLayout(callback)()); 290 | 291 | expect(called).to.equal(1); 292 | 293 | // Shouldn't update again 294 | RNStub.setDimensions(300, 1000); 295 | 296 | styles.onLayout(callback)(); 297 | expect(called).to.equal(1); 298 | }); 299 | 300 | 301 | it('works with aspect-ratio queries', () => { 302 | RNStub.setDimensions(1334, 750); // 16 : 9 303 | 304 | const base = { 305 | someclass: { 306 | color: 'blue' 307 | }, 308 | anotherclass: { 309 | color: 'red' 310 | } 311 | }; 312 | 313 | const result = createStyles( 314 | base, 315 | minAspectRatio(16 / 9, { 316 | someclass: { 317 | fontSize: 12 318 | } 319 | }) 320 | ); 321 | 322 | testStyles(result, { 323 | someclass: { 324 | color: 'blue', 325 | fontSize: 12 326 | }, 327 | anotherclass: { 328 | color: 'red' 329 | } 330 | }); 331 | }); 332 | }); 333 | --------------------------------------------------------------------------------