Learn to disable font scaling in React Native app.

Gautham Vijayan - Aug 26 '23 - - Dev Community

Introduction

In this post we will look into how we can disable font scaling in your react native application. So recently in one of the apps I am working on, the text size in the android version in one of the tester's device was bigger than usual and the design became extremely unstructured and out of bounds. So when investigating the issue, I found out that the end user has increased the size of the font in their settings. So in order to overcome this issue the proposed solution was to disable font scaling and revert it back to one which will retain the font size according to whats being given in the app code. So lets take a look on how we can achieve this in both android and iOS.

Code for android

Go to MainApplication.java in the android folder and add the following code,

import android.util.DisplayMetrics;
import android.view.WindowManager;

@Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
    adjustFontScale(getResources().getConfiguration());
  }

  private void adjustFontScale(Configuration configuration) {
    configuration.fontScale = (float) 1.0;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);
  }
Enter fullscreen mode Exit fullscreen mode

Code for iOS

Go to index.js and add the following code at the bottom of the page.

if (Text.defaultProps == null) {
  Text.defaultProps = {};
  Text.defaultProps.allowFontScaling = false;
  TextInput.defaultProps = TextInput.defaultProps || {};
  TextInput.defaultProps.allowFontScaling = false;
}
Enter fullscreen mode Exit fullscreen mode

For more clarity on where to place the code, you can view the following video for more clarity.

Conclusion

This was a short post, but this will save you a lot of time and retain the text size and design proportions in people's devices who have set their font size to be above the default level. To get to learn more about react and react native you can view my course in Udemy to improve your knowledge revolving around frontend and mobile app development.

https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player