How to use React Native PixelRatio utility class?

Viewed 11355

I have an app written initially for iPhone 6 symulator which has a componend syled with following example values:

const styles = StyleSheet.create({
  headerNav: {
    width: 40,
    height: 40
  },
  headerLogoImage: {
    width: 140,
    height: 140
  },
  footerNavText: {
    padding: 15,
    fontSize: 25
  }
});

Unfortunately when I launched the app on iPad symulator, the size proportions completely collapsed. I know that there is something like PixelRation but documentation is very limited and unclear.

Any idea / suggestions how can I translate these width / height / padding & fontSize to proper values using this PixelRatio class?

3 Answers
// create this utils.ts file
import { PixelRatio } from "react-native";

// dp(123) converts 123px (px as in your mockup design) to dp.
export const dp = (px: number) => {
    return px / PixelRatio.get();
};

// sp(54) converts 54px (px as in your mockup design) to sp
export const sp = (px: number) => {
    return px / (PixelRatio.getFontScale() * PixelRatio.get());
};

Use it like the following way in your styles

const styles = StyleSheet.create({
  footerNavText: {
    padding: dp(123),
    fontSize: sp(54)
  }
})

Note

Do not use dp for fontSize. dp just depends on device screen density (dpi)

sp is used for fontSize only. sp is also just like dp but the difference is that it also depends on user's font settings in his device along with the device screen density (dpi).

Related