<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[cybermonkey - Medium]]></title>
        <description><![CDATA[Engineering Solutions • Nerds on Hire • Elaborated Articles • Best Practices in Software Engineering • Software Development Lifecycle • Productivity Boosting through Automation • JavaScript / TypeScript • ReactJS and React Native • Cloud Infrastructure Management • Full Stack - Medium]]></description>
        <link>https://medium.com/cybermonkey?source=rss----4cd74ca4a2d8---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>cybermonkey - Medium</title>
            <link>https://medium.com/cybermonkey?source=rss----4cd74ca4a2d8---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:41:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cybermonkey" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automated Versioning of React Native Apps for Play Store]]></title>
            <link>https://medium.com/cybermonkey/automated-versioning-of-react-native-apps-for-play-store-c346c18c9f91?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/c346c18c9f91</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 13:36:53 GMT</pubDate>
            <atom:updated>2022-01-26T15:20:13.585Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to <a href="https://code.naishe.in/">Hashnode</a> for my writings. <a href="https://code.naishe.in/automated-versioning-of-react-native-apps-for-play-store">Find this article there!</a></blockquote><p>It started with me forgetting to edit android/app/build.gradle file to increment the version number before uploading to Google Play Store on a Friday evening when I had popcorn getting ready in the oven and friends already started streaming <a href="https://en.wikipedia.org/wiki/Squid_Game">Squid Game</a> in the hall. Play Store console didn’t let me publish the app with the old conflicting version (of course!), and I had to redo the slow build. I needed a way to automate this!</p><figure><img alt="Automate my Fridays!" src="https://cdn-images-1.medium.com/max/400/1*PXjiOF8cO4Qxsrevdatlvg.jpeg" /></figure><p>A couple of PSAs first:</p><ol><li>This article is only about Android releases. It does not go into iOS or React Native Web/Desktop releases.</li><li>If you have FastLane automation, you may want to use <a href="https://github.com/beplus/fastlane-plugin-versioning_android">their versioning plugin</a></li><li>If you are using Expo, look into <a href="https://docs.expo.dev/distribution/release-channels/">their Release Channels</a></li><li>If you are using Microsoft AppCenter Codepush, <a href="https://docs.microsoft.com/en-us/appcenter/distribution/codepush/cli">look into versioning mechanism in CodePush</a></li></ol><p>With that out of the way, let’s get going.</p><p>The demand started when the client wanted to see the version of the binary on the React Native screen. It looks something like this (it used to be a manual update to package.json).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY4n4hSq9Iio3Cy4RS5BnA.png" /><figcaption>The binary version number should be shown on the React Native screen</figcaption></figure><p>In React Native, I found no easy way to fetch the version number of the binary without having to install a massive library like <a href="https://github.com/react-native-device-info/react-native-device-info">react-native-device-info</a>, which sounded like an overkill to me. We know that we can fetch the version from package.json, what if there was a way to keep version numbers in package.json and build.gradle in sync? Auto-may-shun!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPOIxU1WlAwK9YVC8SUVnw.png" /><figcaption>Automation!!! Courtesy <a href="https://workchronicles.com/automation/">https://workchronicles.com/automation/</a></figcaption></figure><p><strong>STEP 1: </strong>Add these two utility functions to android/app/build.gradle</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/944016bd9731ffc89d764d7e34a2b5ce/href">https://medium.com/media/944016bd9731ffc89d764d7e34a2b5ce/href</a></iframe><p>The idea is stolen from <a href="https://stackoverflow.com/a/54146923">this StackOverflow post</a></p><p><strong>STEP 2:</strong> Edit the lines in the block below to utilize our newly minted utility functions at the top of the file.</p><pre>defaultConfig {<br>  applicationId YOUR_APPLICATION_ID<br>  minSdkVersion rootProject.ext.minSdkVersion<br>  targetSdkVersion rootProject.ext.targetSdkVersion<br>  <br>  // Edit these two lines<br>  versionCode 110<br>  versionName 0.1.10<br>}</pre><p>And the block above should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1737efe55df6920bbc75618837ba17e9/href">https://medium.com/media/1737efe55df6920bbc75618837ba17e9/href</a></iframe><p>At this step, if you go ahead, and run ./gradlew bundleRelease, you will see it picks up version value from package.json. If you are OK with manually updating version in package.json and running gradle build, you are done here. But, AUTOMATION?!!</p><p><strong>STEP 3: </strong>yarn and npm both provide a mechanism to update the version of the project (and also automatically tag it for you). See more details here: <a href="https://classic.yarnpkg.com/en/docs/cli/version">https://classic.yarnpkg.com/en/docs/cli/version</a></p><p>Along with updating the version, it also calls a version lifecycle method postversion (also a preversion before the versioning starts). So, if we call our Gradle build as part of the post version step, the following things will happen:</p><ol><li>Yarn will set the new release version (this process is interactive!) in package.json, and create a tag.</li><li>Yarn will kickoff gradle build which will use the new version in package.json</li></ol><p>A win-win!</p><p>Let’s add a postversion script that performs the Gradle build in package.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/461572df493a9e2e1c34ef238265ddb7/href">https://medium.com/media/461572df493a9e2e1c34ef238265ddb7/href</a></iframe><p>And, we are done! Open up your cli and fire the command yarn version and observe the smoothness. Ah-tow-mation, finally!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*lwTrhQb__91NM_n8_xdSyw.png" /><figcaption>Watch the version code and version name derived from version in package.json</figcaption></figure><p>By the way, this is how you fetch the version from package.json on the React Native side:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bf592abe6cfee673748471c858fa3dc/href">https://medium.com/media/9bf592abe6cfee673748471c858fa3dc/href</a></iframe><p>That’s all, folks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c346c18c9f91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/automated-versioning-of-react-native-apps-for-play-store-c346c18c9f91">Automated Versioning of React Native Apps for Play Store</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Linking Push Notifications with React Navigation]]></title>
            <link>https://medium.com/cybermonkey/deep-linking-push-notifications-with-react-navigation-5fce260ccca2?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/5fce260ccca2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[react-navigation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 11:47:02 GMT</pubDate>
            <atom:updated>2022-01-26T14:40:51.490Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to <a href="https://code.naishe.in/">Hashnode</a> for my writings. <a href="https://code.naishe.in/deep-linking-push-notifications-with-react-navigation">Find this article there!</a></blockquote><p>When a user taps on a push notification, they expect to land on the screen the notification is about. When I started to implement this feature, I found no easy way to do it. Although, I had <a href="https://en.wikipedia.org/wiki/Mobile_deep_linking">deep linking</a> figured out, still there was no definitive approach to pass a deep link in push notification and let the link do the magic of taking the user to the intended screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*5sitqIDKb5beX8lePao8lA.jpeg" /><figcaption>We know where to go, but not how to</figcaption></figure><p>React Native Firebase project suggests a simple case of setting initialRouteName in the Navigator tag after extracting the route name from the notification’s data object. Refer: <a href="https://rnfirebase.io/messaging/notifications#handling-interaction">https://rnfirebase.io/messaging/notifications#handling-interaction</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/270a3041813cf6101f434d6f3bba570c/href">https://medium.com/media/270a3041813cf6101f434d6f3bba570c/href</a></iframe><p>This has some obvious drawbacks:</p><ol><li>It seems to be convoluted to handle a situation where screens are scattered in nested Navigator tags across various files.</li><li>It is not obvious how to deal with parameters that may be required to pass to the screen to render it</li><li>We have a perfectly working deep linking mechanism to open the app and auto-navigate with parameters, why can’t we reuse it instead of reinventing the wheel?</li><li>If you try use a solution that lets you redirect to any screen from anywhere without props (<a href="https://reactnavigation.org/docs/navigating-without-navigation-prop/">https://reactnavigation.org/docs/navigating-without-navigation-prop/</a>), you will end up requiring to wait for the navigator to render to have this working. (this was my first solution, but I always ended up triggering the redirection/navigation as soon as the app starts before the Navigator is rendered, causing crash)</li></ol><p>Lucky for us, not long ago, a PR (<a href="https://github.com/react-navigation/react-navigation/pull/8987">https://github.com/react-navigation/react-navigation/pull/8987</a>) sorted this out for us. This article is about how to implement it.</p><p>I assume you have push notification functional. If not, head here to get that working first: <a href="https://rnfirebase.io/messaging/usage">https://rnfirebase.io/messaging/usage</a>. I also assume that you have React Navigation configured, and you are on a version 5.8.10 or above. I am using &quot;@react-navigation/native&quot;: &quot;^5.8.10&quot; in this article.</p><p>Before the linking is configured our app looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ed1987b73810e0536aad2e493a612af/href">https://medium.com/media/3ed1987b73810e0536aad2e493a612af/href</a></iframe><h3>How to configure deep linking</h3><p>Deep linking using React Navigation is well explained here: <a href="https://reactnavigation.org/docs/deep-linking">https://reactnavigation.org/docs/deep-linking</a> However, it took me some time to figure out how to support deep links that have myapp:// as well as https://app.myapp.com/ on Android phones. Trick is to add two different intent filters one for each like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd7521c2fdcd9222bb3bc951d80a307/href">https://medium.com/media/3fd7521c2fdcd9222bb3bc951d80a307/href</a></iframe><p>Now we gotta tell the NavigationContainer that we are reacting to these schemes, so my App.tsx becomes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d58da2c767f53444a1e5bb69ab4d1105/href">https://medium.com/media/d58da2c767f53444a1e5bb69ab4d1105/href</a></iframe><p>At this point, you rebuild your app (commonly, using npx react-native run-android), and you should be able to do the following from your CLI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8d64e2e3c37001a461a183bf246b8c7/href">https://medium.com/media/b8d64e2e3c37001a461a183bf246b8c7/href</a></iframe><p>Now that the deep linking is sorted, we can now freely share the deep link with https scheme in emails and websites and when people click this deep link on their desktops or phones that does not have your app installed, it will take them to your website where they can see the web version or you ask them to install the app nicely. If they have the app, they would find it delightful.</p><h3>Reusing Deep Links in Push Notification</h3><p>Push Notification payload contains a data attribute. You can send any key-value pair as data. If we just pass the deep link as a part of data object and somehow we tell our navigation mechanism to open the link as the first screen instead of the home screen of the app, our work is done.</p><p>React Navigation provides a neat little function in the linking attribute of the NavigationContainer tag. NavigationContainer commonly contains all the application (and definitely all the routes). This function is named getInitialUrl and it is called every time the application launches from the quit state. It is where you will land when the app is opened from a push notification. So, we need to put the logic here to redirect to the appropriate screen. Since we cleverly pass the deep link as a part of push notification, we can let React Navigation deal with it.</p><p>Here is how our linking attribute looks like once we add getInitialUrl function to it (refer: <a href="https://reactnavigation.org/docs/navigation-container#linkinggetinitialurl):">https://reactnavigation.org/docs/navigation-container#linkinggetinitialurl):</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f19a9f342ffb6e815b15aa3a63a1145/href">https://medium.com/media/8f19a9f342ffb6e815b15aa3a63a1145/href</a></iframe><p>But what about the case when we receive the push notification when our app is in the background? You need to add a listener in that case. It looks like this (refer: <a href="https://reactnavigation.org/docs/navigation-container/#linkingsubscribe">https://reactnavigation.org/docs/navigation-container/#linkingsubscribe</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ac5f752bba9b0e351304397040d0f1c/href">https://medium.com/media/8ac5f752bba9b0e351304397040d0f1c/href</a></iframe><p>We are done now. When a push notification is tapped either getInitialUrl is called or onNotificationOpenedApp invokes our listener passed in subscribe method. In both cases, React Navigation handles the incoming URL and redirects to the right screen.</p><p>To test this, go to Firebase console, to the project that’s linked to this app (URL looks something like this: https://console.firebase.google.com/u/0/project/<strong>YOUR-PROJECT-NAME-HERE</strong>/notification/compose), fill out fields. In the Custom Data field, add a link key, with value to one of the valid deep links.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*9d7PLvNW2f_RfCuG" /><figcaption>At the bottom of the screen there is a way to push key-value payload</figcaption></figure><p>Assuming you have your device’s FCM token handy, send a test notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*ifbQfHe9l_D3ERHJ" /><figcaption>Keep your FCM token handy to test your code</figcaption></figure><p>Recline your chair, raise your arms, take a sip of hot tea while you wait for the notification to appear (should not take more than a moment), tap the notification and watch yourself chauffeured to the screen mentioned in the link. You are done for the day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fce260ccca2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/deep-linking-push-notifications-with-react-navigation-5fce260ccca2">Deep Linking Push Notifications with React Navigation</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Over-the-Air Updates in React Native with CodePush: Part 2]]></title>
            <link>https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-2-37df58de6e7e?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/37df58de6e7e</guid>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-push]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 07:45:41 GMT</pubDate>
            <atom:updated>2022-01-26T14:05:06.147Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to <a href="https://code.naishe.in/">Hashnode</a> for my writings. <a href="https://code.naishe.in/mastering-over-the-air-updates-in-react-native-with-codepush-part-2">Find this article there!</a></blockquote><p>This is the second and the final part of the two part series. Find <strong>part 1 </strong>here: <a href="https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-1-faf241a7f84b">https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-1-faf241a7f84b</a></p><p>As happy and dandy as we feel after setting up a pipeline that makes majority of app release bypass the app stores, but the happiness does not last long when you want to do a pre-release testing (Alpha Track in app store) or a beta testing with beta participants, or A/B Testing over 20% of all the users. Only if CodePush could do these for us. Well, you are in luck, CodePush can do all this and more. Let’s explore?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAbJITPUUHMlYGmBG9vqKg.png" /><figcaption>To infinity and beyond</figcaption></figure><h3>An App with Multiple Deployment Keys</h3><p>Let’s try and get our app to do the following:</p><ol><li>Do not pull the updates automatically</li><li>Pull the updates when the programmer or the user wants</li><li>When the updates are pulled programmatically, do not apply the updates immediately (Because that may stun the user. Imagine you are filling up a long from, and just before the submit button was clicked, the app reboots. Not nice.)</li><li>When user switches the deployment key (as in, they switch from Stable version to Beta version or vice versa), load the changes immediately</li><li>Provide an “Open Sesame” to the users to switch between beta and stable versions.</li></ol><h4><strong>MANUAL UPDATES</strong></h4><p>Remember the AppWrappedInCodePush.tsx file from Part 1? It looked laughingly small. We are going to make it the center of our deployment logic. Here is the full version of it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fce8d050d9045016b69c85828d7f54f/href">https://medium.com/media/3fce8d050d9045016b69c85828d7f54f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fea221204515db0de95a2e68a5a1a04d/href">https://medium.com/media/fea221204515db0de95a2e68a5a1a04d/href</a></iframe><p>Let’s read it through:</p><p><a href="https://gist.github.com/naishe/044ac7f2a80a4afa35ddb88b33b42af5#file-appwrappedincodepush-tsx-L35">#35</a>: We are now passing a parameter that tells the CodePush client to <em>not</em> pull the code automatically at the start up.</p><p>As soon as the main application is mounted, the lines <a href="https://gist.github.com/naishe/044ac7f2a80a4afa35ddb88b33b42af5#file-appwrappedincodepush-tsx-L14-L28">#14–28</a> does a couple of things:</p><ol><li>Checks if AsyncStore has a value for the key IS_BETA_USER</li><li>If that key is set to true, sync the codebase with beta stream (because we are using the Staging Key)</li><li>Otherwise, sync the codebase with the stable stream as we pass the Production Key in this case</li><li>Noteworthy, we are setting the installMode to codePush.InstallMode.ON_NEXT_RESTART. Because, from the point of view of the user, this update is happening automatically, and in the background. If you install the code immediately, causing a reboot of the app, the user may not like it. So, we download and wait for the next time the user opens the app to show them the shiny new app.</li></ol><p>As of now, we have not set IS_BETA_USER to anything, so the behavior stays unchanged compared to what we had at the end of Part 1 of this article. But, we can see if somehow we set the IS_BETA_USER value to true in our AsyncStorage, we will start seeing the beta version of the app.</p><h4><strong>SWITCHING BETWEEN STABLE AND BETA VERSIONS</strong></h4><p>I like <a href="https://en.wikipedia.org/wiki/Easter_egg_(media)#:~:text=In%20computer%20software%2C%20Easter%20eggs,otherwise%20serious%20piece%20of%20software.">Easter Eggs</a> in software. What we want to do here is to create a component that looks like plain text information of the software’s version. When a user taps it 8 times, we show them the option to switch between stable and beta versions with a fair warning.</p><p>Here is that component’s code look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d774110f7517b3acf1946863feeaee/href">https://medium.com/media/80d774110f7517b3acf1946863feeaee/href</a></iframe><p>Line number <a href="https://gist.github.com/naishe/6e6eb26db46d4da9b4249b3bde96d072#file-versioninfo-tsx-L58-L78">#58 — #78</a> is the core of it. The rest is just the display logic.</p><p>The toggleBetaUser does the following:</p><ol><li>Sets the IS_BETA_USER value as true or false and stores it in AsyncStore for persistence</li><li>Calls CodePush’s sync method with appropriate key with installMode as IMMEDIATE. This will cause the code to be downloaded from an appropriate release stream and apply it immediately after the download. This will cause the app to reboot and show the downloaded version.</li></ol><p>Now that we have a mechanism to toggle and save the user preference to AsyncStore, our code in the first part of this article would work. If use has set beta mode on, it will sync with the Staging stream, otherwise CodePush will sync with the Production stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLHY6dY_LzMgTxes5VCQJA.jpeg" /><figcaption>From left to right, top to bottom: <strong>1.</strong> Stable version V5, <strong>2.</strong> After the user tapped the version text 8 times, <strong>3.</strong> The user opted-in for beta and assets are downloading, <strong>4.</strong> User is now on beta version</figcaption></figure><h4><strong>FUN THINGS TO DO WHILE SYNCING</strong></h4><p><em>MetaData</em>: codePush.metadata() returns null or a LocalPackage object. Among other things, it has a couple of cool attributes. LocalPackage.appVersion gives you the version of the binary installed on the device. You can see 0.0.4 in the screenshot above. LocalPackage.label gives the CodePush’s resource version installed. It is indicated by v5 in production deployment, and v3 in staging deployment. You can also ask deploymentKey from LocalPackage.</p><p><em>Check for Updates: </em>codePush.checkForUpdate() — This method returns a Promise&lt;null|RemotePackage&gt;. If null, there is nothing to do; all up to date. If it returns a package object, then you can either show to the user that a new update is available or pull the latest.</p><p><em>Synchronize at Will: </em>codePush.sync() — This method kicks off synchronization. This packs a couple goodies. Here is the method signature:</p><pre>1. codePush.sync(<br>2.  options: Object,<br>3.  syncStatusChangeCallback: function(syncStatus: Number),<br>4.  downloadProgressCallback: function(progress: DownloadProgress),<br>5.  handleBinaryVersionMismatchCallback: function(update: RemotePackage)<br>6. ): Promise&lt;Number&gt;;</pre><p><em>options</em> is a JSON object. The most notable attributes are deploymentKey and installMode. The former is the deployment you want the app to sync with, and the latter is how you want the install to happen: immediately, after restart, when the app goes to background or any other way. There are other attributes that can be found in the documentation.</p><p><em>syncStatusChangeCallback</em> is a function with its signature as (syncStatus: Number) =&gt; void, where syncStatus can be any of the values as shown in the enum below. This is what I am using in my code to display the spinner until the syncStatus reaches the UPDATE_INSTALLED state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c4ce7123f2631615d77ea2aedf4f43b/href">https://medium.com/media/6c4ce7123f2631615d77ea2aedf4f43b/href</a></iframe><p><em>downloadProgressCallback</em> is a function with its signature as (progress: DownloadProgress) =&gt; void. You can get really fancy with this. You can use DownloadProgress.totalBytes and DownloadProgress.receivedBytes to show progress bar animation or something.</p><p><em>handleBinaryVersionMismatchCallback</em> can be used to handle situations where you are trying to sync with a deployment whose binary version has diverged from the one on the local machine. This is your opportunity to remind the user to download the latest version from the app store.</p><h4><strong>ENFORCE CERTAIN USERS TO HAVE CERTAIN DEPLOYMENT</strong></h4><p>I hope you do not discriminate against your users on the basis of gender, race, region, belief or anything that they do not have their control over. That’s just not the nicest thing to do. But, it may make sense in certain cases to differentiate the users. What if you want to enable the beta version for all the users whose UserProfile object has isBetaUser = true in the database. Or, maybe, you wanted to roll out the beta version first in certain countries and based on their feedback, you want to decide whether to promote beta version globally.</p><p>In all such cases, wherever you fetching user profile just set AsyncStore.setItem(‘IS_BETA_USER’, `${userProfile.isBetaUser}`)</p><p>Ta-da!</p><p><strong>Why stop here?</strong></p><p>The binary is already embedded with the production key. So, everyone will get the production version to start with. If nothing is altered, they will continue to have production updates. Why can’t we, instead of having a binary value — IS_BETA_USER and hardcoded Deployment Key, dynamically set Deployment Key in AsyncStore and use that key to sync?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*oCD0uen5EWav3J2cvt8Ggg.png" /><figcaption>Different UIs based on your thumb size?</figcaption></figure><p><em>That means, we can set different Deployment Keys for different users and make releases specific to them</em>. For example, if your sync logic looks like this:</p><pre>// undefined userProfile.deploymentKey would use <br>// the key stored in the binary<br>codePush.sync({<br> deploymentKey: userProfile.deploymentKey,<br> installMode: codePush.InstallMode.ON_NEXT_RESTART,<br>});</pre><p>A hypothetical ticket to make a completely new release only to a specific group of users and its workflow would look like this:</p><p><strong><em>TICKET #666</em>:</strong> Make a deployment specific to Indian and Australian users.<br><strong><em>DevOps</em>:</strong> Well, since deployment keys are just a name and an identifier, let’s create one for this ticket</p><pre># Create a new deployment key<br># appcenter codepush deployment add &lt;KEY_NAME&gt; --app &lt;USER&gt;/&lt;APP_NAME&gt;</pre><pre><strong>appcenter codepush deployment add colonial_cousins --app nishant/blog-app</strong></pre><pre>Deployment colonial_cousins has been created for nishant/blog-app with key nkaKawu1CtuHuzzahGIJWq_LOTVcAHEcyLEWt</pre><p><strong><em>DBA</em>:</strong> Let’s set users in India and Australia with deployment_key as nkaKawu1CtuHuzzahGIJWq_LOTVcAHEcyLEWt, others may be null or whatever value they are set to.</p><pre>UPDATE user_profiles <br>SET deployment_key = ‘nkaKawu1CtuHuzzahGIJWq_LOTVcAHEcyLEWt’ <br>WHERE country IN (‘AU’, ‘IN’)</pre><p><strong><em>Release Engineer</em>:</strong> Well, let’s push this release to Indians and Aussies, and close the ticket.</p><pre># Release to specific deployment<br># appcenter codepush release-react -a &lt;USER&gt;/&lt;APP_NAME&gt; -d &lt;KEY_NAME&gt;</pre><pre><strong>appcenter codepush release-react -a nishant/blog-app -d colonial_cousins</strong></pre><p>There we go. We did not touch client code, we did not ask the user to do something special, and still, we have managed to distribute a targeted software update. Isn’t it smooth?</p><h4><strong>A/B TESTING</strong></h4><p>Dark Mode vs Light Mode?<br>Tabs vs drawer?<br>Automated grouping or ungrouped messages?<br>How much time spent on the app on an average?</p><p>Sometimes, you want to be cautious, and release an upgrade to a percentage of users first and then, based on analytical data, you want to decide whether to go ahead with the upgrade or rollback. CodePush makes it as simple as specifying a parameter in the release command. You can specify what percentage of the users get this release. Here is an example</p><pre># appcenter codepush release-react -a &lt;USER&gt;/&lt;APP_NAME&gt; -d &lt;KEY_NAME&gt; -r &lt;PERCENTAGE_ROLLOUT&gt;</pre><pre># The following will roll out the blog app to 20% of the users who are having Production deployment</pre><pre><strong>appcenter codepush release-react -a nishant/blog-app -d Production -r 20%</strong></pre><h4><strong>PROMOTING STAGING RELEASE TO PRODUCTION</strong></h4><p>A common scenario is where once you have tested the app in staging, you want everyone else to have that version. It is a good practice, because it gives you confidence that the tested bundle is going to the production users, not a single bit different.</p><p>You can do it by running the promote command</p><pre>#appcenter codepush promote -s &lt;SOURCE_DEPLOYMENT_NAME&gt; -d &lt;DESTINATION_DEPLOYMENT_NAME&gt; -a &lt;USER&gt;/&lt;APP_NAME&gt;</pre><pre><strong>appcenter codepush promote -s Staging -d Production -a nishant/blog-app</strong></pre><p>Want to be super cautious and promote only to partial users? Just use the -r argument along with the other options above.</p><p>As always, Deployments are just names and identifiers, you can promote any deployment to any deployment.</p><h4><strong>BINARY TARGETED RELEASE</strong></h4><p>Imagine you have two binaries in app stores, one versioned 42.69.8 and another 43.0.0. The older version has some bugs which are fixed in the newer version, but the code in the newer version is incompatible to the code in the older version (maybe because you changed REST response, or added a new node module that’s not there in the older version).</p><p>You want to make a targeted release to the 42.69.8 <em>binary </em>release version.</p><pre># Release to specific deployment</pre><pre># appcenter codepush release-react -a &lt;USER&gt;/&lt;APP_NAME&gt; -d &lt;KEY_NAME&gt; -t &lt;VERSION&gt;</pre><pre><strong>appcenter codepush release-react -a nishant/blog-app -d Production -t 42.69.8</strong></pre><h4><strong>FANCIER THINGS</strong></h4><p>It should be clear to you by now that a deployment is just a name and an identifier associated with it. So, can we use it in our JavaScript as a name and an identifier attached to it? Of course!</p><p>You can use the identifier as the environment name. You can have things like this:</p><pre>// I am assuming you have method somewhere to get currently<br>// used deployment key and a constants object that holds<br>// the deployment keys</pre><pre>const isStaging =<br>  getDeploymentKey() === constants.STAGING_DEPLOYMENT_KEY;</pre><pre>export const API_ROOT_URL = isStaging<br>  ? ‘<a href="https://test.tehbesttodo.app/api">https://test.tehbesttodo.dev/api</a>’<br>  : ‘<a href="https://test.tehbesttodo.app/api">https://production.tehbesttodo.app/api</a>’</pre><p>I think I will close at this. There are many other helpful commands and tricks to use with CodePush, you just need to peek out of the box a little and read the documentation: <a href="https://docs.microsoft.com/en-us/appcenter/distribution/codepush/">https://docs.microsoft.com/en-us/appcenter/distribution/codepush/</a>. Definitely, the latter.</p><p>If you liked the article please do not hesitate to slap the clap button for 50 times. Yes, you can. It is not tiring at all! And share it may be?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37df58de6e7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-2-37df58de6e7e">Mastering Over-the-Air Updates in React Native with CodePush: Part 2</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Over-the-Air Updates in React Native with CodePush: Part 1]]></title>
            <link>https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-1-faf241a7f84b?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/faf241a7f84b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[appcenter]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 02:30:08 GMT</pubDate>
            <atom:updated>2022-01-26T13:37:00.439Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to <a href="https://code.naishe.in/">Hashnode</a> for my writings. <a href="https://code.naishe.in/mastering-over-the-air-updates-in-react-native-with-codepush-part-1">Find this article there!</a></blockquote><p>The initial days of a new mobile app development is a melting pot of frequently added features and improvement, broken-for-certain-devices releases, bugs slipped from the tired eyes, and an out-of-patience-midnight-oil-burning-DevOps with a dark sense of humor. The only thing you<em> do not</em> want at this point is a third party authority with their impractical review policies guarding the doors of the mobile phones where your broken code is pushing the users to the brink of uninstalling the app and writing a scathing review on the store about how poorly developed the app is, ignoring all the hard work done by a team of three night owls surviving on Ramen noodle providing the app for free by paying the bills using AWS free credits (<a href="https://aws.amazon.com/activate/">https://aws.amazon.com/activate/</a>) and digging into their parents savings. No, we do not want this.</p><p><strong>WE WANT SEAMLESS UPDATES, AND WE WANT IT NOW!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weO2uFu8VDhFbgazVLwygA.jpeg" /><figcaption><a href="https://www.freepik.com/vectors/celebration">Celebration</a> vector created by <a href="http://www.freepik.com/">freepik</a></figcaption></figure><h3>Enter CodePush</h3><p>CodePush is a nifty little utility for React Native and Cordova developers to update JavaScript code and bundle assets on client devices on the fly, in minutes after the release. Remember, <em>Not the full app, just the JavaScript and bundle assets.</em> Let me explain this quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*tBiINB0O8sO78CxSB1gncw.png" /><figcaption>CodePush: push your code</figcaption></figure><p>React Native application is made of JavaScript code, image assets, and platform specific binaries bundled by the bundler. CodePush takes responsibility of keeping the JavaScript code and the asset part of the bundle in sync with the latest code that you have uploaded to the CodePush server. When the user installs your app, they get the version of JavaScript and assets that came with the binary that you uploaded to the AppStore or PlayStore. As soon as the user launches the app, the CodePush client that’s installed as a part of your app, checks the latest version of JavaScript bundle on CodePush server and downloads it. Then on, every time you update the bundle on CodePush server, the app syncs itself with it. Doesn’t it sound too similar to how web pages work?</p><figure><img alt="CodePush code synchronization in short" src="https://cdn-images-1.medium.com/max/1024/1*7xGJkwuKHRPdTJ-DAAeWxA.png" /><figcaption>CodePush code synchronization in short</figcaption></figure><p>Let’s clear up our expectations here. This is what we want:</p><ol><li>Set up an AppCenter account and configure our app with the CodePush library</li><li>Release the binary (.aab, .apk, .ipa) to the stores of your choice (or just distribute them over FTP, I don’t care)</li><li>Change some JavaScript, and release it via CodePush</li><li>Restart the app (this time new bundle should be downloaded and installed), and restart again (this time the new bundle should be applied) you should see the new changes</li><li>Allow the users to choose whether they want to become beta user</li><li>Use CodePush deployments to serve bleeding edge updates to beta users while others still have the stable version</li><li>Use CodePush to promote the beta version to production</li></ol><h3>Setting Up CodePush</h3><p>First, we need to create a Microsoft AppCenter account and set up a new project. It is easier than setting up your social media account. <em>It is free</em>, so, if you haven’t yet, go ahead and create an account here: <a href="https://appcenter.ms/">https://appcenter.ms/</a> . I will be waiting for you. Once in, go to Add New &gt; Add New App. Give a recognizable App Name, select OS either Android or iOS, select React Native as Platform and click Add New App button.</p><p>Select the App, from the left menu under Distribute, click CodePush. From the center, click “Create Standard Deployments”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuyUGv0w7DtsQhY3JYAkXg.png" /><figcaption>CodePush is hidden under Distribute menu</figcaption></figure><p>Now, you should see a “Everything is Ready” message with info on how to integrate CodePush with your app and how to release it. On the top right corner, you should be seeing a spanner🔧wrench icon. Click it. You should be seeing two identifiers: one titled “Staging” and another named “Production”. Two channels essentially. Two streams if you will. The Names do not matter. You can use any of these for production release. But, no one likes to watch the world burning. So, let’s assume, we will use the Production key for production deployments and Staging for staging release (or beta testers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAHx2EQV7rnCPKyfELcR-Q.png" /><figcaption>What’s in a name: deployment names and corresponding keys</figcaption></figure><p>For the remaining of the article, whenever we are talking about Deployment Keys, Keys, Production Deployment Key, Staging Deployment Key, or Beta Deployment key, we are talking about one or both of these values. (Over the course of the article, I created two different projects in CodePush, so, the values in the text below may not match the values in the image above)</p><h3>Integrate CodePush with the App</h3><p>With our CodePush server configuration done, we are ready to do what we love the most. Code. (Really?) CodePush comes under Microsoft’s AppCenter service which provides much wider services than just managing release synchronizations.</p><p><strong>Install AppCenter CLI</strong></p><p>Just follow the command and replace appropriate values wherever it makes sense.</p><pre>// Get the CLI<br><strong>npm install -g appcenter-cli</strong></pre><pre>// Login<br><strong>appcenter login</strong></pre><pre>// View your apps, we will use these names later<br><strong>appcenter apps list</strong></pre><pre>// View the environments and corresponding deployment keys<br>// appcenter codepush deployment list -k --app &lt;USERNAME&gt;/&lt;APPNAME&gt;<br><strong>appcenter codepush deployment list -k --app nishant/blog-app</strong></pre><pre>┌────────────┬───────────────────────────────────────┐<br>│ Name       │ Key                                   │<br>├────────────┼───────────────────────────────────────┤<br>│ Production │ Jbach1Qk_achQarrrhNOA9zwVlJnruLsa9jsr │<br>├────────────┼───────────────────────────────────────┤<br>│ Staging    │ jhai-muzz27Nt7Y11KLp-cBsNA22EGjGHEYfr │<br>└────────────┴───────────────────────────────────────┘</pre><h3>Code Changes</h3><p>Install the appropriate version of react-native-code-push as mentioned here: <a href="https://github.com/microsoft/react-native-code-push">https://github.com/microsoft/react-native-code-push</a></p><p>As of now here is the versions of react-native-code-push and corresponding react-native versions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f929389237c140be26b6257aa21226f/href">https://medium.com/media/0f929389237c140be26b6257aa21226f/href</a></iframe><p><strong>WRAP THE APP</strong></p><p>Wrap the main app component with CodePush’s higher order component. You can do it the way it is explained here in their official documentation: <a href="https://github.com/microsoft/react-native-code-push#plugin-usage">https://github.com/microsoft/react-native-code-push#plugin-usage</a></p><p>I personally do not like too many things in my App.tsx or App.jsx file. In a realistic case, you must already be wrapping the main App component with various Context providers like Theme, Redux, GraphQL client, Authorization provider et-cetera. Adding more noise to this is just… well, not so pretty. But prettiness apart, CodePush has a separate concern altogether. CodePush is a continuous delivery solution provider, and the rest of the code is either to rendering the UI or to perform the business logic.</p><p>So, I created a separate class component that wraps the App component with CodePush component. And, edited index.js to use this new class component. Here is what they look like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64907361f5f2049856ae2248848d259f/href">https://medium.com/media/64907361f5f2049856ae2248848d259f/href</a></iframe><blockquote><strong>💡 No CodePush in local env?!</strong></blockquote><blockquote>If you don’t wanna activate CodePush while you are in the debugging mode. You can conditionally apply CodePush wrapper like this:</blockquote><pre>export default __DEV__ ? App : codePush(AppWrappedInCodePush);</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0470fe6a01d7f21a48d15ec84c50bd1/href">https://medium.com/media/c0470fe6a01d7f21a48d15ec84c50bd1/href</a></iframe><p>Now, we need to do OS specific changes. Please note that OS specific instructions below are for React Native 0.60.0 and onwards. For older versions, <a href="https://docs.microsoft.com/en-us/appcenter/distribution/codepush/">refer the official documentation</a>.</p><p><strong>Android</strong></p><p>For the Android side of the code, here are diffs and list of files to be changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9884802b79340a203790f569631cbcf5/href">https://medium.com/media/9884802b79340a203790f569631cbcf5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e977f22a59bdfad084757689c9a1fc9/href">https://medium.com/media/9e977f22a59bdfad084757689c9a1fc9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79816165d6003c490501c84622772c53/href">https://medium.com/media/79816165d6003c490501c84622772c53/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20ae5552a60257be4551a91b37569d81/href">https://medium.com/media/20ae5552a60257be4551a91b37569d81/href</a></iframe><blockquote><strong>🐞 POSSIBLE BUG!</strong><br>Got a message in late 2021, someone saying CodePush sync wasn’t working on Android. Back then, I tested on a new project, it worked. Recently (early 2022), a freelance project I was working on I saw the issue. A little bit of searching around led me to this GitHub post: <a href="https://github.com/microsoft/react-native-code-push/issues/1961">CodePushUnknownException</a>. In case you are facing this, please make the following change to your android/app/build.gradle file, add the following lines under android.defaultConfig block:</blockquote><pre>// The code below is one single line!<br>resValue &#39;string&#39;, &quot;CODE_PUSH_APK_BUILD_TIME&quot;, String.format(&quot;\&quot;%d\&quot;&quot;, System.currentTimeMillis())</pre><p><strong>iOS</strong></p><p>iOS side requires fewer changes, here they are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2ebf1e83a93049944b005a46c3dbed6/href">https://medium.com/media/e2ebf1e83a93049944b005a46c3dbed6/href</a></iframe><p>You need to add the CodePushDeploymentKey in your Info.plist and set its value to the Production key from the CodePush console.</p><p>You can use XCode to add this, as show below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kq8kff26Du3ZaijWqHWgQA.png" /><figcaption>Add CodePush Production Deployment Key as a new attribute to Plist, use your own</figcaption></figure><p>Or you can edit the Info.plist directly, it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a8b32ba59a5bd6bce162abc0bb581d/href">https://medium.com/media/74a8b32ba59a5bd6bce162abc0bb581d/href</a></iframe><p>Phew!!! A lot of changes, feeling anxious? I think that’s the right response. Now, you need to build the production release binary and distribute it to the users (via AppStore, PlayStore, and/or by just sharing the APK or IPA file).</p><p>Cool. The users have the app up and running. Now, make a change (or many changes) to JavaScript files. Perform a CodePush release, here how you do it:</p><pre>// Make your changes and then<br>// appcenter codepush release-react -a &lt;USERNAME&gt;/&lt;APPNAME&gt; \<br>// -d Production<br><strong>appcenter codepush release-react -a nishant/blog-app -d Production</strong></pre><pre>Detecting android app version:<br>Using the target binary version value &quot;0.0.4&quot; from &quot;android/app/build.gradle&quot;.</pre><pre>Running &quot;react-native bundle&quot; command:<br>[-- snip --]<br>index.js --platform android<br>Welcome to React Native!<br>Learn once, write anywhere<br>[-- snip --]</pre><pre>Releasing update contents to CodePush:<br>Successfully released an update containing the &quot;/var/folders/89/s5j46yyd7xn1s9ctl_5td2d80000gn/T/code-push202072-97439-5f5fka.gokh2/CodePush&quot; directory to the &quot;Production&quot; deployment of the &quot;blog-app&quot; app.</pre><p>Give it a few moments, and then open the app (maybe keep it up for a minute or two so that the sync completes), close the app, and open the app again. You should be seeing the new changes.</p><p>Congratulate yourself. 🎉</p><p>At this point, we have the pipeline set. Since the majority of the code movement in React Native applications happen in JavaScript, whenever we want to release the updated code to our users, we’d just push the code through CodePush and have it reflected immediately on the users devices without waiting for AppStore or PlayStore to approve it.</p><p>A lot of us would be happy with just this. However, wouldn’t it be better if we could have two release streams — one for a smaller audience, the beta testers who would get the preview version and another the stable release for everyone else? When we are happy with the beta version, we’d promote it to stable release for everyone else to see it.</p><p>Shouldn’t we have more control over the updates? Is there a way to manually kick off the update? Should we ask the user whether they want the update? Can we show update progress? Can we rollback a bad release? Since you mentioned preview and stable versions, can we use this for A/B testing? Can we have more than two deployment keys? Can we remotely control the user’s version (deployment key) by setting key specific to them on their user profile when they log in? Can we use these keys to switch the environment as in, one key point to test environment APIs and other to production APIs? Also, when is CodePush not enough and we require a binary release to the stores?</p><p>We will discuss all these fun things in the next part.</p><p>Fresh from the oven, the part two is here: <a href="https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-2-37df58de6e7e">https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-2-37df58de6e7e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf241a7f84b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/mastering-over-the-air-updates-in-react-native-with-codepush-part-1-faf241a7f84b">Mastering Over-the-Air Updates in React Native with CodePush: Part 1</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating React Native Major Version]]></title>
            <link>https://medium.com/cybermonkey/updating-react-native-major-version-191ed52810d1?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/191ed52810d1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-update]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 09:42:48 GMT</pubDate>
            <atom:updated>2020-07-27T11:46:30.034Z</atom:updated>
            <content:encoded><![CDATA[<p>I hated ReactNative’s YellowBox during development. So, I was eagerly awaiting for the version 0.63.x to switch to. It has much saner <a href="https://reactnative.dev/blog/2020/07/06/version-0.63#logbox">LogBox</a>. At <a href="https://cybermonkey.dev/">CyberMonkey</a>, we try to keep our dependencies updated. We know, it isn’t as easy as just updating the React ecosystem libraries in package.json. So, let’s get going?</p><figure><img alt="Upgrade are scary, never cute :-(" src="https://cdn-images-1.medium.com/max/640/1*c76_hlfOyy-7TI4winSzVw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/ooceey-13528103/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4897080">ooceey</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4897080">Pixabay</a></figcaption></figure><p><strong>BRANCH YOUR CODE</strong></p><p>If you haven’t already, please backup your working code because this process may backfire. I strongly suggest you use a source code management tool like Git or SVN. Assuming, you are using git, let’s make a local branch:</p><pre># Creates a branch named rn_upgrade_0_62_2_to_0_63_2<br>git checkout -b rn_upgrade_0_62_2_to_0_63_2</pre><p><strong>USING REACT NATIVE UPGRADE HELPER</strong></p><p>Every react native major release has more than a handful files changed. It would be a lot of work to create two bare bone React Native projects, one with the currently used version of React Native and another, with the target version, and then figure out the changes to bring into our codebase. Luckily for us, React Native upgrade helper does exactly that.</p><figure><img alt="React Native Upgrade Helper Configuration" src="https://cdn-images-1.medium.com/max/1024/1*waQ11WQotzbJvK1bsn8HYA.png" /><figcaption>React Native Upgrade Helper Configuration</figcaption></figure><ol><li>Go to <a href="https://react-native-community.github.io/upgrade-helper">https://react-native-community.github.io/upgrade-helper</a></li><li>Select your and target versions</li><li>Click the cog on the top right, and set the name of the app. You can find this in package.json as name field. (Or look into ios/Podfile for line saying target &#39;NameOfYourApp&#39; do)</li><li>Click “Show me how to upgrade” button.</li></ol><p>Voila! you have all the diffs. It’s time to do the dirty job. You need to go file by file and make appropriate changes. You may feel like just pasting the whole files, and it may work, but if you have changes in files like gradle files, plist, AppDelegate.m etc, you may face some issues.</p><p>Tip: If you use VS Code as your editor finding those files with keyboard shortcut ⌘ + p on macOS or Control + p on Windows/*nix OSes, is extremely easy.</p><p><strong>BEFORE YOU BUILD</strong></p><p>We have changes files, before we go ahead, we should clean the slate for new changes</p><ol><li>Delete node_modules directory (along with yarn.lock or package-lock.json)</li><li>npm install or yarn install to bring the dependencies afresh.</li><li>Kill any running package bundler and emulator</li><li>Clear cache react-native start --reset-cache</li><li>Deploy the newly upgraded code npx react-native run-android or npx react-native run-ios</li></ol><figure><img alt="Left: Ugly YellowBox from version 0.62.2; Right: Pretty looking LogBox from version 0.63.2" src="https://cdn-images-1.medium.com/max/1024/1*qsAVHyW4rdHVTyGTIvhoAQ.jpeg" /><figcaption>Left: Ugly YellowBox from version 0.62.2; Right: Pretty looking LogBox from version 0.63.2</figcaption></figure><p>Congratulations! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191ed52810d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/updating-react-native-major-version-191ed52810d1">Updating React Native Major Version</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multiple Language Support in React Native: Part 3]]></title>
            <link>https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/d8091339c767</guid>
            <category><![CDATA[multiple-language-support]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 12:50:48 GMT</pubDate>
            <atom:updated>2022-01-26T08:40:36.563Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to Hashnode for my writings. <a href="https://code.naishe.in/mastering-multiple-language-support-in-react-native-part-3">Find this article there!</a></blockquote><p>In this final chapter of the three part tutorial, we will discuss some of the advanced features offered by i18next, these topics will include rendering dynamic strings using features such as interpolation, formatting, setting timezone locale, pluralization, nesting, context, and JSON objects and arrays.</p><p>If you want to learn about configuring localization and internationalization with i18next, jump to <strong>part 1</strong> of this series here: <a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332</a></p><p>If you want to learn about organizing translations for a medium to large application and providing language change control to the users, hop on to <strong>part 2</strong> of the series at <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d</a></p><p>If you want to view code for this part, please clone the repo at: <a href="https://github.com/naishe/rn_multilanguage">https://github.com/naishe/rn_multilanguage</a> and checkout part_3 branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*JWthw4tqBCgz8i_EaF9-zg.jpeg" /><figcaption>i18next toolset: If all you have is a hammer, everything looks like a nail</figcaption></figure><p>With all the formality done, let’s earn some elbow grease, shall we?</p><p><strong>INTERPOLATION</strong></p><p>The most frequently used utility is interpolation. Interpolation allows you to provide a templated string like { howdy: “Hey {{ username }}, how are you doing today?”} and render it with the dynamic value you pass from the rendering code.</p><pre>t(“howdy”, { username: “Nishant”});<br>// returns: Hey Nishant, how are you doing?</pre><p>But, life isn’t easy. Most of the time you have things like user object and userBill object and you need to print something like Hey &lt;username&gt;, your account has been suspended until your last bill Rs &lt;bill amount&gt; is cleared. Here is the trick:</p><pre>// String template<br>accountSuspended: &quot;Hey {{ user.username }}, your account has been suspended until your last bill Rs {{ userBill.total }} is cleared.&quot;</pre><pre>// Rendering<br>const user = {<br> username: &quot;Nishant&quot;,<br> intelligenceLevel: 7<br>};</pre><pre>const userBill = {<br> total: 420.69,<br> paymentDueDate: &quot;May the fourth&quot;<br>};</pre><pre>t(&quot;accountSuspended&quot;, { user, userBill })<br>// returns: Hey Nishant, your account has been suspended until your last bill Rs 420.69 is cleared.</pre><p><strong>FORMATTING</strong></p><p>You can create your custom formatting function and pass its name along with the string to be formatted to i18next.t and it will do it for you. You need to register your formation functions in init configuration under the interpolation attribute as format key.</p><p>For example, if you want to write a formatting function that takes a number and prints the Indian flag that many times if language code is hi, Hindi, else prints world emoji those many times. If it is not a number it returns whatever is passed. The code looks like as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35ba22ee40d19507dae71918c7a1bb94/href">https://medium.com/media/35ba22ee40d19507dae71918c7a1bb94/href</a></iframe><p>I haven’t found a great use case where I would use formatting. One of the most useful things we can do is we can instruct Moment.js (<a href="https://momentjs.com/">https://momentjs.com/</a>) to use locale whenever the language preference changes.</p><p>You just need to add a listener after initializing i18next, like this:</p><pre>// i18next configuration file</pre><pre>//Make sure you import the locales<br>import &#39;moment/min/locales&#39;;<br>import moment from &#39;moment&#39;;</pre><pre>// — removed for brevity — </pre><pre>i18n.on(&#39;languageChanged&#39;, (lng: string) =&gt; moment.locale(locale));</pre><p>A caveats here. Moment does not load all the locales so you need to import the locales.</p><p>Let’s have a look how formatting code looks like:</p><pre>&lt;Text&gt;{t(&#39;flagsCount&#39;, {count: 3})}&lt;/Text&gt;</pre><pre>&lt;Text&gt;<br>  Moment.js Locale 42 minutes ago:<br>  {moment().subtract(42, &#39;minutes&#39;).fromNow()}<br>&lt;/Text&gt;</pre><p>And it renders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2haInCoV_UebcWkqNm3Iw.png" /><figcaption>Format in action, also automatically switches locale for Moment.JS</figcaption></figure><p><strong>PLURALIZATION</strong></p><p>Different languages handle pluralization differently. It is not uncommon to come across uses where you need to display difference strings depending on the quantity of subject matter. Here is an example in English:</p><p><em>Singular</em>: 1 knife found during the autopsy<br><em>Plural</em>: 3 knives found during the autopsy</p><p>To display different content based on the number passed to i18next.t function, you need to define two keys, one regular key to be used for singular cases and another key suffixed with _plural for plural usage.</p><pre>{<br>  autopsy: “{{count}} knife was found during the autopsy”,<br>  autopsy_plural: “{{count}} knives were found during the autopsy”,<br>}</pre><pre>// returns:<br>// t(‘autopsy’, {count: 1}) = 1 knife was found during the autopsy<br>// t(‘autopsy’, {count: 7}) = 7 knives are found during the autopsy</pre><p>However, this way of writing sentences does not have human touch to it, it is still too beep-boop-1-krrr-knife-was-found-isque. We would probably want something like this:</p><p>No knife was found on the dead body.<br>A knife was found during the autopsy.<br>7 knives were found during the autopsy. Looks like a work of a deranged maniac.</p><p>To that end, let’s try specifying what number triggers which translation. So, for example, a set of keys like this should serve our purpose:</p><pre>{<br> autopsy_0: “No knife was found on the dead body.”,<br> autopsy: “A knife was found during the autopsy.”,<br> autopsy_plural: “{{ count }} knives were found during the autopsy. Looks like a work of a deranged maniac.”,<br>}</pre><pre>// returns:<br>// t(‘autopsy’, {count: 0}) = 0 knives were found during the autopsy. Looks like a work of a deranged maniac.</pre><pre>// t(‘autopsy’, {count: 1}) = A knife was found during the autopsy.</pre><pre>// t(‘autopsy’, {count: 7}) = 7 knives were found during the autopsy. Looks like a work of a deranged maniac.</pre><p>Hmmm, it did not work that way expected. I was disappointed to learn this.</p><p><strong>Limitations of Plural: </strong>The variable has to be named count. I would have liked a case where you can tell which field in a JSON object controls the pluralization. But, this is just a minor inconvenience.</p><p>You need to know which locale supports what kind of pluralization, so you cannot arbitrarily create keys key_0, key_1, key_2, and so on and expect it to work. You can use this lookup utility to see what suffixes work for your locale <a href="https://jsfiddle.net/sm9wgLze">https://jsfiddle.net/sm9wgLze</a></p><p>Also, have a look at this issue: <a href="https://github.com/i18next/i18next/issues/1220">https://github.com/i18next/i18next/issues/1220</a></p><p>Let me explain what I just said, for example:</p><p>hi supports key (for count = 1) and key_plural (for count other than 1, even zero and negative counts)</p><p>en supports key (for count =1) and key_plural (for all other values of count)</p><p>ar — Arabic — supports key_0 (for count=0), key_1 (for count=1), key_2 (for count=2), key_3 (for count=3 to 10), key_4 (for count=11 to 99), key_5 (for count=100 and above)</p><p>So, pluralization does not look much fun anymore. If you still want to use count based translation, the good people from i18next have provided a post processor <a href="https://github.com/i18next/i18next-intervalplural-postprocessor">https://github.com/i18next/i18next-intervalplural-postprocessor</a> You can learn about it on their GitHub repo.</p><p><strong>CONTEXT</strong></p><p>Context can be thought of as “which variation of a key can be used in a given context”. Case in point, ThatMate (<a href="https://thatmate.com/">https://thatmate.com</a>) is a sexual and mental health awareness platform for teenagers. We have been planning to use binary and gender neutral pronouns in English locales. Here is quick glance on what it looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*uMB7j93yTrPTjg177qYXDg.png" /><figcaption>Learn more about gender spectrum at <a href="https://lbgtrc.msu.edu/educational-resources/pronouns/">https://lbgtrc.msu.edu/educational-resources/pronouns/</a></figcaption></figure><pre>{<br>  loveThyself_she: “She is in love with herself”,</pre><pre>  loveThyself_he: “He is in love with himself”,</pre><pre>  loveThyself_they: “They is in love with themself”, <br>  //yes, “is” is the right helping verb for they here</pre><pre>  loveThyself_ze: “Ze is in love with hirself”,</pre><pre>  loveThyself_ey: “Ey is in love with eirself”,<br>}</pre><p>We want the appropriate translation to appear on screen based on what the user has chosen as their preferred pronoun. So, if a user’s profile says their preferred pronoun is “ey”, we want then to see the last variations of “loveThyself”. My context here is “ey”</p><p>Context is a really powerful tool. For example, Hindi, ‘hi’ does not have equivalent five pronouns. It has just three pronouns, for male, for female, and a gender neutral. We need to fallback on gender neutral pronouns in Hindi for ‘ze’ and ‘ey’ pronouns. But that does not mean we will have to create five keys the same as the case above and have ‘ze’, ‘ey’ and ‘they’ have the same content. We can just define, three and non matching will fallback to suffix-less translation. So, the Hindi keys look like this:</p><pre>{<br>  loveThyself_she: ‘वह अपने से प्रेम करती है।’,<br>  loveThyself_he: ‘वह अपने से प्रेम करता है।’,<br>  loveThyself: ‘वो अपने से प्रेम करते हैं।’,<br>}</pre><p>And to access these contexts you need to call `i18next.t` with key and context as options. So, for a code that look like this:</p><pre>const genderPronouns = [&#39;she&#39;, &#39;he&#39;, &#39;they&#39;, &#39;ze&#39;, &#39;ey&#39;];</pre><pre>// — code removed for brevity</pre><pre>{ <br>  genderPronouns.map((context) =&gt; <br>    (&lt;Text key={context}&gt;{t(&#39;loveThyself&#39;, {context})}&lt;/Text&gt;)<br>  )<br>}</pre><p>The outcome in en language code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN_BNFt5l8zgXIocX4gVfg.png" /><figcaption>All five genders have their appropriate pronouns</figcaption></figure><p>And, the same code render the following in hi language:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t18RQNdIJdG90bPewqOgrw.png" /><figcaption>Hindi has just three forms of the pronouns</figcaption></figure><p>If you look closely, even though you do not get the script, the last three fallback to the translation that does not have any context (no suffix).</p><p>— — — — — — —</p><p>There are only a few good things in the world. You can count them if you think hard and long lying on your back well fed and healthy in a serene environment. Context is one of those. Remember how disappointing it was that pluralization could not help us with cases where we specified translations for count = 0, 1, and for all other values of count. Context with help of interpolation can do that. The following code gives the desired result:</p><pre>&lt;Text&gt;{t(‘autopsy’, {count: 0, context: ‘0’})}&lt;/Text&gt;<br>&lt;Text&gt;{t(‘autopsy’, {count: 1, context: ‘1’})}&lt;/Text&gt;<br>&lt;Text&gt;{t(‘autopsy’, {count: 7, context: ‘7’})}&lt;/Text&gt;</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RkZLOsynTmQWcloP9ujAQ.png" /><figcaption>Pluralization combined with context can do what Pluralization should have done</figcaption></figure><p><strong>OBJECTS AND ARRAYS</strong></p><p>Language resources are just a big JSON object with string keys and values that could string, JSON objects or arrays. Sometimes you may want i18next to return you the object or array instead of string. One such case appeared when we wanted to display a random funny loading message from a list of loading messages. If we get a list of strings, we could just do list[ Math.floor( Math.random() * list.length ) ]. Luckily for us, we can retrieve a key as a JSON object or array, just by instructing i18next so.</p><pre>{<br>  funnyLoadingMessages: [<br>    &quot;Maybe the server gnomes are sleeping&quot;,<br>    &quot;What is taking so long?&quot;,<br>    &quot;Damn! I can believe I paid for this app.&quot;,<br>    &quot;One mississippi, two mississippi, …&quot;,<br>  ]<br>}</pre><p>And the following code returns the array</p><pre>t(&quot;funnyLoadingMessages&quot;, { returnObjects: true });</pre><p>You can apply interpolation and pluralization on the return as well.</p><p><strong>REFERENCING OTHER KEYS</strong><br>You can reference one key into another key’s translations. For example, something like this:</p><pre>{<br>  salutation: &quot;howdy!&quot;,<br>  goodnight: &quot;$t( salutation ) What are you doing so late up? I am signing off. Good night, m8!&quot;<br>}</pre><pre>t(&quot;goodnight&quot;);<br>// returns: howdy! What are you doing so late up? I am signing off. Good night, m8!</pre><p>And as always, interpolation, context, etc works as expected.</p><p>This concludes the third and the final chapter of this tutorial. But, by no means it is a substitute of the documentation offered by i18next (<a href="https://www.i18next.com/">https://www.i18next.com/</a>) and react-i18next (<a href="https://react.i18next.com/">https://react.i18next.com/</a>), so if you want to dive deeper please look into those resources.</p><p>Here is how the final app looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AeY7CiSN1kHaD9ptWZOSQ.jpeg" /><figcaption>Left is Hindi locale, and right is English</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pvj9EO0t8hFAStpZJn8V7g.jpeg" /><figcaption>Of course, you’d give the repo a try, but just in case, you wanted to see</figcaption></figure><p>Please press the clap button 50 times (yes, you can) if you liked the article. I wrote this article while looking for a complete How-To for multiple language support on React Native in the middle of a break neck ongoing sprint, so there is a good chance that I have made buckets of spelling and grammatical mistakes. Please be kind and let me know if you come across mistakes of any kind. I hope my tardy sense of humor did not bore you to death.</p><p><strong>Part 1</strong> <a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332</a></p><p><strong>Part 2</strong> <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8091339c767" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767">Mastering Multiple Language Support in React Native: Part 3</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multiple Language Support in React Native: Part 2]]></title>
            <link>https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/d33262acc21d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[multiple-language-support]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 05:03:19 GMT</pubDate>
            <atom:updated>2022-01-26T08:07:51.388Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have moved to Hashnode for my writings. <a href="https://code.naishe.in/mastering-multiple-language-support-in-react-native-part-2">Find this article there!</a></blockquote><p>This article runs in three parts. <strong>Part one</strong> can be accessed here: <a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332</a></p><p><strong>Part 3</strong> is here: <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767</a></p><p>If you are looking for the code for part 2, checkout part_2 branch of the GitHub repo at <a href="https://github.com/naishe/rn_multilanguage">https://github.com/naishe/rn_multilanguage</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*86KS1mJ0yDROoDBgtiRwAg.jpeg" /><figcaption>Getting serious about translation (courtesy Pxfuel <a href="https://www.pxfuel.com/en/free-photo-qfskg">https://www.pxfuel.com/en/free-photo-qfskg</a>)</figcaption></figure><p>In the <a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">last part</a>, we have got the basics of multiple language support done. We could set up a project, guess the best possible language, store and retrieve language preference and display content in the language. It sounds like we are done, but for any serious medium to large project, there are a bunch of things you want to do to avoid pulling your hair over the course of app development. In this article, we will do some advanced things. Here is the list of things we will do:</p><ol><li>Splitting the translations into manageable files and move the JSON away from the config file</li><li>Allow users to change the language and apply it across the app</li><li>[Let’s leave it for part 3] Rendering dynamic strings using features such as interpolation, formatting, setting timezone locale, pluralization, nesting, context, and JSON objects and arrays</li></ol><p><strong>Organizing translations: Namespaces and Deep Objects</strong></p><p>What to want when it comes to organizing translations? We want each language to have its own directory, and we want translations to split in multiple files. Maybe, I want to have a “common” file that has translation for commonly used texts like OK, Cancel, Back, and so on. I also want one file for each screen, so I want translations for Home screen in home file, and Settings screen in settings file. So, this is what I want as far as folder structure is concerned</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*2a_A5OVbdwJiOBxJNvooeQ.png" /><figcaption>Folder Structure of Translation Files</figcaption></figure><p>Where my common.ts, homePage.ts, and index.ts looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6281f092cb8cc3e4df05c84e3404bfb7/href">https://medium.com/media/6281f092cb8cc3e4df05c84e3404bfb7/href</a></iframe><p>So, essentially, when we import en from &#39;./en&#39;, we get a JSON that looks like:</p><pre>{<br> common: {<br>  ok: “OK”,<br>  cancel: “Cancel”<br> },</pre><pre> homePage: {<br>  welcome: “Welcome to i18Next!”<br> }<br>}</pre><p>In i18n lingo, common and homePage are called namespaces. And, we can refer to the contents of a namespace by referring to the key with the namespace as prefix with colon as separator. So, to access ok key from common namespace, we need to do the following, t(&#39;common:ok&#39;) and it will render the value of ok from the selected language’s common file.</p><p>What if we want another layer of grouping? What if we want to group translation of a dialogue box component within the home page. Like this:</p><pre>{<br> homePage: {<br>  welcome: “Welcome to i18Next!”,<br>  title: “An unnecessarily lengthy tutorial”,</pre><pre>  dialogue: {<br>   title: “An unnecessary dialogue box”,<br>   close: “Go back to home page”<br>  }<br> }<br>}</pre><p>We can use dot notation to traverse through the nested JSON object. Here, t(“homePage:title”) will return “An unnecessarily lengthy tutorial” and t(“homePage:dialogue.title”) will return “An unnecessary dialogue box”.</p><p>Now that the file organization and nested translation is sorted out, we are mostly OK with it. But, wouldn’t it be good if we do not have to type namespace for the most commonly used namespace? It would be so nice, if we could, just do t(“cancel”) and we get the value from the common namespace. Well, we are in luck. We can specify default namespace in configuration and for all the cases where a namespace is not mentioned it will look into default namespace.</p><p>At this point, out i18next configuration looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc6f1844c07adffba95ca1e2d91eb46d/href">https://medium.com/media/fc6f1844c07adffba95ca1e2d91eb46d/href</a></iframe><p>And, a code looks like this,</p><pre>&lt;Text&gt;homePage NS: {t(&#39;homePage:welcome&#39;)}&lt;/Text&gt;<br>&lt;Text&gt;Deafult NS: {t(&#39;ok&#39;)}&lt;/Text&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPRxQOh94rrBuPeR1fEE4w.png" /><figcaption>Yeah, I see the typo!</figcaption></figure><p><strong>Allow Users to Switch Language</strong></p><p>It will be a powerful display of your confidence if you choose a user’s preferred language for them and not let them choose the language they want your app to be. But, we do not live in that kind of world where installing an app is a long term commitment. So, we need to provide a way to let user change the language and it is as easy as calling i18n.changeLanguage(“YOUR_LANGUAGE_CODE”)</p><p>When you call changeLanguage it changes language for the whole application at the same time, the cacheUserLanguage is also called with the language code of the newly selected language. If you remember from the last part, this is where our logic to store the language code also exists. So, as soon as we change language, the new change gets applied and the preference is stored. Neat!</p><p>A small React Native utility component that does the whole heavy lifting for you would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd1d70a04d97304912093003b7b0d76b/href">https://medium.com/media/fd1d70a04d97304912093003b7b0d76b/href</a></iframe><p>And the outcome looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*5r3C0Oocls_-naGlyu1W1A.png" /><figcaption>The default View (language is picked from user preference)</figcaption></figure><p>As you click English, the whole app changes to English and it is stored to AsyncStore for future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*fA3vaoDQNFA0kNOPkWYIMQ.png" /><figcaption>Everything is in English</figcaption></figure><p>Well, at this point, the majority of us are done, except for the annoying ones with their “what ifs”. A bunch of advanced features will be discussed in part 3. Hope to see you there.</p><p><strong>Part 1 </strong><a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332</a></p><p><strong>Part 3</strong> <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d33262acc21d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d">Mastering Multiple Language Support in React Native: Part 2</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Language Support in React Native: Part 1]]></title>
            <link>https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332?source=rss----4cd74ca4a2d8---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa6966b62332</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[multiple-language-support]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Nishant Neeraj]]></dc:creator>
            <pubDate>Mon, 20 Jul 2020 18:55:44 GMT</pubDate>
            <atom:updated>2022-01-26T06:45:01.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Multiple Language Support in React Native: Part 1</h3><blockquote>I have moved to Hashnode for my writings. <a href="https://code.naishe.in/mastering-multiple-language-support-in-react-native-part-1">Find this article there!</a></blockquote><p>This article runs in three parts. If you are looking for code, please use part_1 branch of this repo: <a href="https://github.com/naishe/rn_multilanguage">https://github.com/naishe/rn_multilanguage</a></p><p>The <strong>second part</strong> can be accessed at <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d</a></p><p><strong>Part 3</strong> is here: <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*039k43kCUQB1V2alC8mBfw.png" /><figcaption>Hello?</figcaption></figure><p>If you are serving a multilingual audience through your app, it becomes quickly obvious that supporting the languages of the demography will give you an edge over the singular language app. Working on <a href="https://thatmate.com/">ThatMate</a>’s mobile app that serves sexual and mental health education to children and young adults in India, we came to realize that we will have to support multiple Indian languages along with English sooner than later. Luckily, for us, the React Native ecosystem makes it really simple. This article will explain how we did it.</p><p>Please be aware that fully localization is much more than just multiple language support, it includes currency conversion, date and time format, RTL (right to left) language and UI direction support, calendar type, timezone, whether they use metric system, and temperature unit among other things. This article is about supporting multiple languages, however, it can easily be extended to provide full localization support.</p><p><strong>NOTE:</strong> This tutorial assumes that your project is created using React Native CLI (as in npx react-native init AwesomeProject ). If you are using Expo, there is an excellent guide on Expo website <a href="https://docs.expo.io/versions/v38.0.0/sdk/localization/).">https://docs.expo.io/versions/v38.0.0/sdk/localization</a>). The Expo guide uses the i18n-js library for internationalization. If you want to use i18next, you will have to use expo-localization instead of react-native-localization as the dependency.</p><p>If you are trying this on a fresh project, create a new React Native project:</p><pre>npx react-native init rn_multilanguage --template react-native-template-typescript</pre><pre>cd rn_multilanguage</pre><p>Install dependencies:</p><pre>npm install --save i18next react-i18next react-native-localize @react-native-community/async-storage</pre><p>Where the installed libraries are:</p><p><strong>react-native-localize:</strong> The library that provides helper functions to figure out the device’s localized preferences like languages, timezone etc. Read more here:<a href="https://github.com/react-native-community/react-native-localize"> https://github.com/react-native-community/react-native-localize</a></p><p><strong>i18next:</strong> Our internationalization library. Read more about this here:<a href="https://www.i18next.com/"> https://www.i18next.com/</a></p><p><strong>react-i18next:</strong> This library provides nice binding with React and React Native projects using hooks, higher order components and also providers Trans — translator component. Read more about it here:<a href="https://react.i18next.com/"> https://react.i18next.com/</a></p><p><strong>@react-native-community/async-storage:</strong> Local storage library, we will use this library to persist the language preference over app restarts</p><p>Now that we have our workspace set up, let’s start coding. In general, this is what we want:</p><ol><li>Initialize internationalization at the beginning of the app</li><li>Check user’s stored language preference, and show the content in that language</li><li>If this is the first time user launching our app or there is <em>no</em> language preference saved, find the best suited language for the user by providing all supported languages and looking into device’s language preference</li><li>If no matching language is found in step fallback to default language</li></ol><p><strong>Initialize i18next for React</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7492fa6ea1fb6d14717dd775dd4566b9/href">https://medium.com/media/7492fa6ea1fb6d14717dd775dd4566b9/href</a></iframe><p>Let’s break this code down:</p><p>Line #46 to #68 is where the initialization is happening. We are passing a custom language detector to be used. Also, passing initReactI18next from react-i18next to enable React and i18next integration. Then we pass the initialization settings.</p><p>Initialization has three parts:</p><p><strong>Resources:</strong> A JSON object that contains the supported language codes and for each language code, we have a key and the equivalent translation in that language. In the code snippet, we have two language codes: en for English and hi for Hindi. We have added the same keys to both the languages and the associated values are the representation of that key in the respective languages. So, if you do t(&quot;Welcome to React&quot;) the users with Hindi preference would see “रियेक्ट तथा रियेक्ट-आई १८ एन में आपका स्वागत है” and the users with English as their preference would see “Welcome to React and react-i18next”.</p><p>You might be thinking that this way of setting translation will quickly become unwieldy. And, perhaps what if you want to organize the translations in a more nested way, or maybe how gender or pluralization could be handled? Worry not. Let’s get through the basics, then we will see how we can make our life much easier by keeping translations in separate files and how to use nesting.</p><p><strong>React:</strong> React specific settings go here. I have disabled suspense here. Otherwise, you will get a warning in the lines of</p><pre>Exception has occurred: Error<br>Error: I18nextWithTranslation suspended while rendering, but no fallback UI was specified.<br><br>Add a &lt;Suspense fallback=...&gt; component higher in the tree to provide a loading indicator or placeholder to display.</pre><p>You will either have to wrap your components in &lt;Suspense&gt; tag like it is suggested here:<a href="https://react.i18next.com/latest/using-with-hooks#translate-your-content"> https://react.i18next.com/latest/using-with-hooks#translate-your-content</a> or you can disable Suspense like I did.</p><p><strong>Interpolation:</strong> i18next provides you to use template strings and interpolate them at the render time. For example the following translation can be evaluated dynamically</p><pre>{<br> &quot;sayMyName&quot;: &quot;My name is {{ name }}&quot;<br>}</pre><p>When you do the following:</p><pre>i18next.t(“sayMyName”, “&lt;Nishant&gt;”)<br>// returns: My name is &amp;lt;Nishant&amp;gt;</pre><p>This is to avoid XSS attacks. Read more here:<a href="https://www.i18next.com/translation-function/interpolation#unescape"> https://www.i18next.com/translation-function/interpolation#unescape</a></p><p>However, in React Native we do not have this issue. We want strings to be rendered as is. So, we want the last interpolation to return us “My name is &lt;Nishant&gt;” and for that, we want to turn off the escapeValue.</p><p>Now that we know how to initialize i18next. Let’s check out how to detect the user language. And, that is the fun part.</p><p>I18next follows a middleware plugin sort of architecture. If you have used Express.js, you might be familiar with the concept. In essence, the library exposes a specification, inputs to the plugin and expected outputs from the plugin. In our case, our plugin code spans from line #10 to line #44.</p><p>We specify that it is a languageDetector plugin (#11), the detection happens asynchronously (#14). At #15, it provides you with various objects that might be required for your plugin to initialize. I left it empty because I did not need it, but I mentioned it here in case you wanted to do something. Then comes the meat of the code, the detect function. Detect function is provided with a callback function that takes the detected language. Note that the callback function is passed when we mention async is true. If your detection is synchronous, then you can set async:false and return the language code from the detect function. Let’s dig into this detect function, shall we?</p><p>At line #23, we look into the AsyncStorage for previously stored language code. I know that I have stored it with the key APP_LANG (I will tell you later where I store the user preference, for now assume that language code is stored in APP_LANG and APP_LANG is a name I provided. You can use your own key if you did not like it). If fetching the language code errors out or returns a falsy value, we will try guessing the user’s preference.</p><p><strong>Guessing User’s Language Preference:</strong> It only makes sense to suggest a language if we somehow get a list of user’s acceptable languages prioritized by users preference for those languages and compare that list with the languages that we provide for the app and then find which language fits the best. Luckily for us, React-Native-Localize has a tool that does exactly that.</p><p>At line #33,</p><pre>const bestLng = RNLocalize.findBestAvailableLanguage([&#39;en&#39;, &#39;hi&#39;]);</pre><p>We ask react-native-localize to find the best suitable language among the provided language codes by comparing it with the user’s system language preference. In the case shown in the screenshot below, the function will return “hi”, Hindi, as the best language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFrtv92ybT-bI1mXubRW3w.png" /><figcaption>User’s Language Preference: Tamil first, Hindi second, and English third</figcaption></figure><p>In case there is no common language between the list of languages you support and the list of languages in the user’s language preference, RNLocalize.findBestAvailableLanguage returns undefined and that is our clue to return the fallback language. In our case, we are returning en, English, as our fallback language at line #35.</p><p>Lastly, if it is a sunny day, the stored language will be fetched from local store and we will return this as I did at line #38.</p><p><strong>Storing User Language Preference:</strong> My favorite part of the plugin is the cacheUserLanguage method, because it centralizes the logic to store user selection. This method is called every time after detect is called and, as we will see later in this post series, when the user opts to change the language.</p><p><strong>Step 2: Integration with the App</strong></p><p>At this point, we have configured i18next to work with React to guess the best language and to store the selected language permanently. What’s the wait? Let’s integrate with our React Native code. It’s as simple as importing this file in the application main entry file, which is, for most of us mortals, either App.tsx or App.jsx.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07fde7d7a1c43f94b4393572ddc51b14/href">https://medium.com/media/07fde7d7a1c43f94b4393572ddc51b14/href</a></iframe><p>At this point our app looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVhEZezNBR-v8xVDjR4DwA.png" /><figcaption>Automatically selected Hindi and served the content</figcaption></figure><p><strong>Are we done yet? </strong>Well, almost. We haven’t given a way to change the language. Neither have we looked at how to split translations in different files. How to interpolate, and how to return an object or array of strings. We do not know how to handle gender specific sentences or plural and singular sentences. Let’s take a break. And continue this in the next article.</p><p><strong>Part 2:</strong> <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-2-d33262acc21d</a><br><strong>Part 3:</strong> <a href="https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767">https://medium.com/cybermonkey/mastering-multiple-language-support-in-react-native-part-3-d8091339c767</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6966b62332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybermonkey/multiple-language-support-in-react-native-part-1-fa6966b62332">Multiple Language Support in React Native: Part 1</a> was originally published in <a href="https://medium.com/cybermonkey">cybermonkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>