Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Intl properly in Android React Native app

I'm trying to use number formatter of Intl, which works perfectly on iOS and when debugger is attached to either iOS or Android, but only fails on Android without debugger attached due to outdated JSC in Android.

After a bit research I've found two possible solutions:

  • Use Intl polyfill
  • Use custom JSC in Android

I tried Intl polyfill first like this after installing intl and react-intl using yarn:

//in my app's index.js
if (!global.Intl) {
    global.Intl = require('intl');
}

Though it still says ReferenceError: Can't find variable: Intl.

Then I gave up and tried to include custom JSC (I've confirmed that custom AAR is referenced correctly) though I still get the same error. No matter what I do I can't get Intl to get running on Android without debugger attached.

What am I doing wrong? (I'm on React Native 0.59.9)

like image 989
Can Poyrazoğlu Avatar asked Jul 08 '19 23:07

Can Poyrazoğlu


4 Answers

Small update, as of React Native v0.60+ you can define intl+ version of the lib.

In your app/build.gradle:

def jscFlavor = 'org.webkit:android-jsc-intl:+'

and have it implemented below in your dependencies:

dependencies {
    ...
    if (enableHermes) {
        ...
    } else {
        implementation jscFlavor
    }
}
like image 70
Simon Avatar answered Oct 18 '22 23:10

Simon


If disabling Hermes is not an option in your app/build.gradle, and you cant use org.webkit:android-jsc-intl:+ then Intl polyfill can fix the issue:

npm install intl

in the code:

import 'intl';
import 'intl/locale-data/jsonp/en'; // or any other locale you need
like image 15
Hamid Tavakoli Avatar answered Oct 18 '22 23:10

Hamid Tavakoli


npm i intl

After that import

import "intl";

import "intl/locale-data/jsonp/en";

And then use Intl

For eg:-

{new Intl.NumberFormat("en-IN", {
                  style: "currency",
                  currency: "INR",
                }).format(
                  (travelTimeInformation?.duration.value *
                    SURGE_CHARGE_RATE *
                    multiplier) /
                    100
                )}
like image 4
jay Avatar answered Oct 18 '22 21:10

jay


If you're using custom JSC then don't forget to import the international version as explained in the read me of JSC Android Buildscripts:

For React Native version 0.59, replace original artifact id with android-jsc-intl

dependencies {
+   // Make sure to put android-jsc at the the first
+   implementation "org.webkit:android-jsc-intl:r241213"
+
    compile fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}
like image 1
TimeWalker Avatar answered Oct 18 '22 23:10

TimeWalker