Last active
January 13, 2020 09:17
-
-
Save WazzaJB/ddb7776900c4a256e3717e73e58df622 to your computer and use it in GitHub Desktop.
React Native Responsive Helper Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Dimensions } from 'react-native'; | |
/** | |
* Wrap a style rule in this responsive function to process dimensions | |
* @param {object} Object of queries containing style objects | |
*/ | |
const responsive = (queries, dim = 'window') => { | |
const { width, height } = Dimensions.get(dim); | |
let styles = []; | |
Object.keys(queries).forEach(query => { | |
const style = queries[query]; | |
let failedRules = query.split('and').map(v => { | |
let [rule, value] = v.split(':').map(s => s.trim()); | |
// Return true to pass rule, false to fail | |
switch (rule) { | |
case 'minWidth': | |
return width >= value; | |
case 'maxWidth': | |
return width <= value; | |
case 'minHeight': | |
return height >= value; | |
case 'maxHeight': | |
return height <= value; | |
case '': | |
return true; | |
default: | |
return false; | |
} | |
}).filter(v => v !== true); | |
// If all rules were met (failedRules array is empty), add to array | |
if (!failedRules.length) { | |
styles.push(style); | |
} | |
}); | |
return Object.assign(...styles); | |
}; | |
export default responsive; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment