Margin or Padding Shorthand in React Native
I created this helper function in a past project:
const getShortHand = (style: string, ...values) => {
if (values.length === 1) {
return { [style]: values[0] }
}
const _genCss = (...values) => ({
[style + 'Top']: values[0],
[style + 'Right']: values[1],
[style + 'Bottom']: values[2],
[style + 'Left']: values[3],
})
if (values.length === 2) {
return _genCss(values[0], values[1], values[0], values[1])
}
if (values.length === 3) {
return _genCss(values[0], values[1], values[2], values[1])
}
return _genCss(values[0], values[1], values[2], values[3])
}
export const padding = (...values: Array<number | string>) => getShortHand('padding', ...values)
export const margin = (...values: Array<number | string>) => getShortHand('margin', ...values)
The usage is similar with the normal css shorthand:
const styles = StyleSheet.create({
button: {
...padding(12, 20),
},
}
When using plain React Native styles you can rewrite your css above to
{ marginVertical: 10, marginHorizontal: 20 }
Otherwise the above syntax can be achieved if you're using something like styled-components, which uses css-to-react-native under the hood.