Skip to content

Instantly share code, notes, and snippets.

@richardgill
Last active May 3, 2016 08:14
Show Gist options
  • Save richardgill/676a384534070906a4832ced7becbdda to your computer and use it in GitHub Desktop.
Save richardgill/676a384534070906a4832ced7becbdda to your computer and use it in GitHub Desktop.
Normalize RN styles - Code for iPhone 6s and it should work across all devices.
import _ from 'lodash'
import { Dimensions } from 'react-native'
const { height } = Dimensions.get('window')
const iphone6Height = 667
const fieldsToNormalize = [
'fontSize',
'width',
'height',
'margin',
'marginTop',
'marginBottom',
'marginLeft',
'marginRight',
'padding',
'paddingTop',
'paddingBottom',
'paddingLeft',
'paddingRight',
]
const normalizeFont = (size) => {
let newSize = size
if (height === 568) {
newSize = size * (1 / 1.2)
} else if (height === 667) {
newSize = size
} else if (height === 736) {
newSize = size * (1.4 / 1.2)
}
return newSize
}
const normalizeValue = (styleKey, value) => {
if (styleKey === 'fontSize') {
return normalizeFont(value)
}
return (height / iphone6Height) * value
}
function normalizeStyle(style) {
const normalizedStyle = _.mapValues(_.pick(style, fieldsToNormalize), (value, key) => normalizeValue(key, value))
return {
..._.omit(style, fieldsToNormalize),
...normalizedStyle
}
}
export default function normalizeStyles(styles) {
return _.mapValues(styles, (style) => normalizeStyle(style))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment