Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change font family based on different languages using react-native

I am developing a mobile app using react-native. The app needs to handle multiple languages (English and Sinhala). Some mobile phones support Sinhala fonts and display them correctly. But some of not support the Sinhala language. For that, I want to load the font using the font folder within the app.

I add font folder to the app and linking them using the react-native link. But font not loading correctly.

  1. I want to know how to load custom fonts to react-native
  2. How to load font family dynamically, when user change language

enter image description here

enter image description here

like image 852
Dushyantha Avatar asked Nov 06 '22 10:11

Dushyantha


1 Answers

I might be a little late but I found this solution that you can use to dynamically change the font based on the language.

1.

import NativeModules from 'react-native'

2.

Then use this inline if to change the language when the user changes the device locale.

fontFamily: ((NativeModules.I18nManager.localeIdentifier == 'az_AZ') ? 'Alice' : 'DesirasNonCommercial')

If you have more than two languages, you can create a module and implement a function to check the locale and return the corresponding font. Then you can simply use the returned value in the fontFamily. Also If you have a button to manually change the language, you can modify the function above and add an event listener to return the appropriate fontFamily when the language changing button is triggered.

like image 100
Ali KHalili Avatar answered Nov 11 '22 04:11

Ali KHalili