Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example for using React Native's Stylesheet setStyleAttributePreprocessor method?

We've noticed the StyleSheet has a method called setStyleAttributePreprocessor which:

Sets a function to use to pre-process a style property value. This is used internally to process color and transform values. You should not use this unless you really know what you are doing and have exhausted other options.

I wonder if there is an example of use. Basically we would like to scale width and height according to the screen's size all across the app:

const {
    width,
    height
} = Dimensions.get('window');

const widthScale = width / 320;
const heightScale = height / 568;
like image 441
Guy Avatar asked Oct 22 '25 22:10

Guy


1 Answers

Ended up doing this:

import {StyleSheet} from 'react-native';
import {Dimensions} from 'react-native';

const {
    width,
    height
} = Dimensions.get('window');

const widthScale = width / 320;
const heightScale = height / 568;

const widthRatioKeys = {
    fontSize: true,
    paddingHorizontal: true,
    paddingLeft: true,
    paddingRight: true,
    padding: true,
    marginHorizontal: true,
    marginRight: true,
    marginLeft: true,
    margin: true,
    borderRadius: true,
    borderWidth: true,
    right: true,
    left: true,
}

const heightRatioKeys = {
    paddingVertical: true,
    paddingTop: true,
    paddingBottom: true,
    marginVertical: true,
    marginTop: true,
    marginBottom: true,
    height: true,
    minHeight: true,
    lineHeight: true,
    top: true,
    bottom: true,
}


Object.keys(widthRatioKeys).forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, (value) => {
        return value * widthScale;
    });
});

Object.keys(heightRatioKeys).forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, (value) => {
        return value * heightScale;
    });
});
like image 97
Guy Avatar answered Oct 25 '25 19:10

Guy