<?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[Stories by Faraz Khan on Medium]]></title>
        <description><![CDATA[Stories by Faraz Khan on Medium]]></description>
        <link>https://medium.com/@frzkn?source=rss-d3c6d3a81763------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ajgHILy03z0EFFE5wmCorw.jpeg</url>
            <title>Stories by Faraz Khan on Medium</title>
            <link>https://medium.com/@frzkn?source=rss-d3c6d3a81763------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:56:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frzkn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Towards Reproducible Android Apps — Locking Gradle Dependencies]]></title>
            <link>https://citymall.engineering/towards-reproducible-android-apps-locking-gradle-dependencies-c0ff2eaacde2?source=rss-d3c6d3a81763------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0ff2eaacde2</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Faraz Khan]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 05:24:49 GMT</pubDate>
            <atom:updated>2023-07-21T12:31:22.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards Reproducible Android Apps — Locking Gradle Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFig7ljNhjosIHyWr-2LXA.png" /></figure><p>Lately, I’ve been reading a lot on the topic of reproducibility, It is an essential factor to achieve to be able to have a snapshot-like version of your codebase, This article aims towards covering all the points to make our React Native Gradle (Android) builds as deterministic as we can.</p><blockquote>Note: This article’s context revolves around React Native. However, if you are a Native Android Developer or Flutter Developer, you will find it equally comprehensible to understand and follow.</blockquote><p><a href="https://en.wikipedia.org/wiki/Reproducible_builds">Reproducible builds,</a> also known as deterministic compilation, offer a process that guarantees the ability to reproduce the code consistently. When source code is compiled using deterministic compilation, it will always generate the same output which can be used to go back in time and reproduce the build anytime.</p><p>When creating reproducible builds, along with the source code, the specific versions of the dependencies used during the compilation process also remain constant. This means developers can recreate the built application precisely, even if the dependencies have been updated or changed since then.</p><p>Having this ability to go back in time and reproduce a build with the exact same dependencies is valuable. It ensures that any future modifications or bug fixes can be tested and validated against the same conditions under which the original build was created. This capability helps in identifying and resolving issues that may cause due to changes in dependencies or other external factors.</p><p>In this article, we will explore the practical aspects of implementing reproducible builds in React Native apps. By the end, you will have a better understanding of reproducible builds and the necessary knowledge to apply them effectively in your React Native Android projects.</p><p>If you’d like to see the source code directly <a href="https://github.com/frzkn/LockAndroidGradleDeps/commits/main">click here</a>.</p><h4>Let&#39;s begin!</h4><p>Often at times, you must’ve noticed that when we switch back to the previous version branch of our app there are more often than not few build issues that require manual intervention. But this isn’t supposed to be this way, Cause you’ve for sure tagged the commit with the release version on your source control. Your project may even contain a package-lock.json / yarn.lock file, So what’s the problem?</p><p>There are a lot of factors that contribute to our builds being nondeterministic the most important ones being,</p><ol><li>Dependencies relying on dynamic assets</li><li>The development environment and build tools</li><li>Dependencies auto-resolving to a higher version</li></ol><p>Let&#39;s take a look at each one in depth,</p><h4>1. Dependencies relying on dynamic assets</h4><p>Assets that are pulled in from a proprietary server on build time are known as dynamic assets, This one is the most difficult problem to tackle as you do not have any control over the assets as they might change without any prior notice, <br>I faced this issue in one of our projects wherein the builds started breaking due to an incorrectly 9-patched image, Honestly, I do not know how to fix this one other than making sure the packages you’re adding maintain version control for the dynamically serving assets as well. One way to fix this would be to create a local proxy that serves you the same assets on every build.</p><h4>2. The development environment and build tools</h4><p>Developers often work with different versions of tools such as Node.js, React Native CLI, and Gradle, as well as varying versions of the Android SDK, Gradle plugins, and dependencies. These differences can lead to varying build outputs, ultimately affecting the final APK.</p><p>To ensure reproducibility, it is crucial to maintain consistency in the development environment and build tools across the entire team. In the context of React Native, One can run npx react-native info on every system config update and log the information in the readme.md file so that everyone else can refer to the system info and set their environment the same. This can be done with a single command in npm scripts like the following, <a href="https://github.com/frzkn/LockAndroidGradleDeps/commit/d3e85f0ec09ddc5e5d3ab0cbc652ba6fbaac036f">GitHub link</a></p><pre>&quot;log-systeminfo&quot;: &quot;react-native info &gt; systeminfo.log&quot;</pre><p>Lastly, I personally prefer yarn over npm and have this block in package.json files to block users from using npm unknowingly. Note you also need to add an .npmrc file with content asengine-strict=true as shown <a href="https://github.com/frzkn/LockAndroidGradleDeps/commit/4f11beb487a0ae7405cb95740a9fae8d46cd2cdd#diff-e813096d69c49812e40e00be9ac8fa14d77f0ec1f97ab4c45cb096b3bedd35deR1">here</a>, otherwise, it would only warn and not block npm operations.</p><pre>  &quot;engines&quot;: {<br>    &quot;npm&quot;: &quot;Please use Yarn to avoid versioning issues&quot;<br>  }</pre><h4>3. Dependencies auto-resolving to a higher version</h4><p>In our package.json we shouldn’t add packages with ^ in front of their version name below is an example of the same</p><pre>&quot;react-redux&quot;: &quot;^7.2.0&quot;,</pre><p>Now react-redux is a very reputable package that follows <a href="https://semver.org/">semantic versioning</a>, So we do not necessarily need to remove the ^ in this case, we can be assured that no breaking change will be introduced in the minor/patch version. But that isn’t the case with every package on npm, I’ve noticed several packages accidentally or unknowingly pushing a breaking change with the minor/patch version bump which causes the app or sometimes even the builds to break. So it is important to avoid ^ as much as possible to maintain stability and take another step towards reproducible builds.</p><p>Node package managers such as npm and yarn do create their respective .lock files whenever you initially install all the dependencies<br>These lock files make sure to resolve the same version of packages that were resolved in the initial install. But if someone were to make a last moment change to package.json, The .lock file will get updated in the CI and not get committed, chances are that these last minute .lock file updates are even missed by QAs. So it is important to add --frozen-lockfile (in the case of yarn). This will throw an error anytime the dependencies from the .lockfile differs to ensure that .lock file is always the source of truth.</p><p>If you started as a JavaScript developer first and an app developer second like me then chances are that you were already familiar with the things I talked about in this section. You might even be doing all of these but still failing to create reproducible builds.</p><h4><strong>Locking gradle dependencies</strong></h4><p>The dependencies we pull in from npm has native modules in it as well and very much like package.json, Gradle also allows you to set dynamic dependency versions like the following</p><pre>implementation &#39;com.google.firebase:firebase-messaging:20.2.+&#39;</pre><p>To which Android Studio complains with the following message avoid using + in version numbers; can lead to unpredictable and unrepeatable builds, Which can be easily resolved when we’re ourselves plugging these packages into our build.gradle file. The problem arises when we pull in some external dependency.</p><p>The solution to this is to make use of gradle.lockfilefile sounds pretty straightforward which it actually is but I was shocked to realize how uncommon is this amongst many Android projects. Unlike npm / yarn the gradle.lockfile the file is not created automatically but requires some changes in our project levelbuild.gradle file</p><h3>Locking Gradle dependencies comes to the rescue!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fhighornerygalago&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fhighornerygalago&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1000" height="584" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eefd4826629e6f7570524e6d8ebb811/href">https://medium.com/media/7eefd4826629e6f7570524e6d8ebb811/href</a></iframe><p>I looked up the topic and it is indeed possible to have a development flow with locked dependencies. It is not widely known and isn’t used as much as its benefits.</p><p>Before we jump into the implementation, Let&#39;s explore some of the issues which I personally faced as a Mobile Developer which I remember could’ve been avoided or handled in an easier way with gradle dependency locking. Some of the instances which broke Android production code I can recollect are:</p><ul><li><a href="https://stackoverflow.com/questions/56697811/play-services-ads-18-0-0-get-crash">Play-services-ads 18.0.0 get crash</a></li><li><a href="https://github.com/CleverTap/clevertap-react-native/issues/161#issuecomment-840475128">error: cannot find symbol CleverTapAPI.setUIEditorConnectionEnabled(false) · Issue #161 · CleverTap/clevertap-react-native</a></li><li><a href="https://stackoverflow.com/questions/69208613/getting-error-while-running-react-native-app">Getting Error While Running React Native App</a></li><li><a href="https://stackoverflow.com/questions/69037481/android-app-wont-build-the-mincompilesdk-31-specified-in-a-dependencys-an">Android app won&#39;t build -- The minCompileSdk (31) specified in a dependency&#39;s androidx.work:work-runtime:2.7.0-beta01</a></li></ul><p>In all of the instances, The application broke either at compile time or worse, when pushed to production without any changes made to the codebase dependencies. Let&#39;s see how we can fix it with the help of enabling dependency locking.</p><h4>Implementing Gradle Locking</h4><p>In this tutorial, we will start by creating a new React Native application. You can either follow along with the steps or directly access the final repository. The repository <a href="https://github.com/frzkn/LockAndroidGradleDeps">can be found here.</a></p><pre>&gt; npx react-native@latest init LockAndroidGradleDeps</pre><p>Let&#39;s make the necessary changes to the project level build.gradle file.<br>Feel free to add configurations.all block to your existing subprojects block if one exists already in your project.</p><pre>buildscript {<br>    ext {<br>        buildToolsVersion = &quot;33.0.0&quot;<br>        minSdkVersion = 21<br>        compileSdkVersion = 33<br>        targetSdkVersion = 33<br>        ndkVersion = &quot;23.1.7779620&quot;<br>    }<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>    dependencies {<br>        classpath(&quot;com.android.tools.build:gradle:7.3.1&quot;)<br>        classpath(&quot;com.facebook.react:react-native-gradle-plugin&quot;)<br>    }<br>}<br>+<br>+subprojects { <br>+    configurations.all {<br>+       it.resolutionStrategy.activateDependencyLocking()<br>+  }<br>+} <br>+<br>+<br>+dependencyLocking {<br>+    lockAllConfigurations()<br>+}</pre><p>The subprojects block specifies that the code within it should be applied to all subprojects of the current project. This block configurations.all specifies that the code within it should be applied to all configurations of each subproject. Gradle’s activateDependencyLocking() method, part of the ResolutionStrategy interface, provides support for dependency locking, allowing developers to lock the resolved versions of their dependencies and prevent unexpected changes in dependency versions for more reproducible builds. Let&#39;s create the lock file now!</p><pre>&gt; cd android &amp;&amp; ./gradlew app:dependencies --write-locks</pre><p>If you’re familiar with native Android, you would probably know the ./gradlew app:dependencies command, this is a Gradle command that generates a report of the dependencies of the app project. The ./gradlew part of the command specifies that the Gradle Wrapper should be used to execute the command. Note the app:prefix, which signifies that the dependencies task should be executed for the app project. This task generates a report that shows the dependencies of the app project, including transitive dependencies and their resolved versions. Useful for debugging dependencies-related issues in general. Since we added activeDependencyLocking logic to all of our subprojects passing --write-locks flag will write all the module-level dependencies, transitive dependencies, and their resolved versions to a app/gradle.lockfile file.</p><pre>~/LockAndroidGradleDeps/android/app<br>&gt; ls<br>gradle.lockfile   ...    ...    ...</pre><p>When we open this file, we see a comment stating that it is a Gradle-generated file for dependency locking. The comment also warns against making manual edits to the file as they can break the build and advises that the file should be part of source control. Therefore, we should commit this file source control.</p><pre># This is a Gradle generated file for dependency locking.<br># Manual edits can break the build and are not advised.<br># This file is expected to be part of source control.<br>...</pre><p>By following these steps, your dependencies are now locked.</p><p>A successful build verifies that the dependencies used, align with those frozen in the lock state, even if new versions matching the dynamic selector have been found in the upstream.</p><p>To verify this, you can add a new React Native library to your app. For example, let’s add a popular alternative to React Native’s Image component and run the app on Android to see the results, and check this out!</p><pre>~/LockAndroidGradleDeps/android/app <br>&gt; yarn add react-native-fast-image</pre><pre>FAILURE: Build failed with an exception.<br><br>* What went wrong:<br>Could not determine the dependencies of task &#39;:app:processDebugResources&#39;.<br>&gt; Could not resolve all task dependencies for configuration &#39;:app:debugRuntimeClasspath&#39;.<br>   &gt; Resolved &#39;com.github.bumptech.glide:gifdecoder:4.12.0&#39; which is not part of the dependency lock state<br>   &gt; Resolved &#39;com.github.bumptech.glide:annotations:4.12.0&#39; which is not part of the dependency lock state<br>   &gt; Resolved &#39;com.github.bumptech.glide:disklrucache:4.12.0&#39; which is not part of the dependency lock state<br>   &gt; Resolved &#39;androidx.exifinterface:exifinterface:1.2.0&#39; which is not part of the dependency lock state<br>   &gt; Resolved &#39;com.github.bumptech.glide:okhttp3-integration:4.12.0&#39; which is not part of the dependency lock state<br>   &gt; Resolved &#39;com.github.bumptech.glide:glide:4.12.0&#39; which is not part of the dependency lock state</pre><p>The dependencies the Gradle is trying to resolve are not part of the dependency lock state. To fix we can either update our lockfile as a whole by running the same command or by manually updating the locked state for this particular dependency</p><pre>&gt; ./gradlew app:dependencies --write-locks<br><br>    OR<br><br>&gt; ./gradlew app:dependencies --update-locks &#39;com.github.bumptech.glide:*&#39;</pre><p>When we try again we see that our app successfully builds. Now let&#39;s see what happens When I try to force a different version of an existing library in our build.gradle by adding the following block to our app/build.gradle</p><pre>implementation(&quot;com.github.bumptech.glide:gifdecoder:4.10.0&quot;)  {<br> force = true<br>}</pre><p>The next time we try to run the application, We are as expected, presented with this error stack trace.</p><pre>FAILURE: Build failed with an exception.<br><br>* What went wrong:<br>Could not determine the dependencies of task &#39;:app:compileDebugJavaWithJavac&#39;.<br>&gt; Could not resolve all task dependencies for configuration &#39;:app:debugCompileClasspath&#39;.<br>   &gt; Could not resolve com.github.bumptech.glide:gifdecoder:4.10.0.<br>     Required by:<br>         project :app<br>      &gt; Cannot find a version of &#39;com.github.bumptech.glide:gifdecoder&#39; that satisfies the version constraints:<br>           Dependency path &#39;LockAndroidGradleDeps:app:unspecified&#39; --&gt; &#39;com.github.bumptech.glide:gifdecoder:4.10.0&#39;<br>           Constraint path &#39;LockAndroidGradleDeps:app:unspecified&#39; --&gt; &#39;com.github.bumptech.glide:gifdecoder:{strictly 4.12.0}&#39; because of the following reason: dependency was locked to version &#39;4.12.0&#39;<br><br>   &gt; Could not resolve com.github.bumptech.glide:gifdecoder:{strictly 4.12.0}.<br>     Required by:<br>         project :app<br>      &gt; Cannot find a version of &#39;com.github.bumptech.glide:gifdecoder&#39; that satisfies the version constraints:<br>           Dependency path &#39;LockAndroidGradleDeps:app:unspecified&#39; --&gt; &#39;com.github.bumptech.glide:gifdecoder:4.10.0&#39;<br>           Constraint path &#39;LockAndroidGradleDeps:app:unspecified&#39; --&gt; &#39;com.github.bumptech.glide:gifdecoder:{strictly 4.12.0}&#39; because of the following reason: dependency was locked to version &#39;4.12.0&#39;</pre><p>This is the default behavior of the locking mechanism of the Gradle, In addition to this Gradle also provides us with two different locking strategies</p><blockquote>Strict mode</blockquote><blockquote>In this mode, in addition to the validations above, dependency locking will fail if a configuration marked as <em>locked</em> does not have lock state associated with it.</blockquote><blockquote>Lenient mode</blockquote><blockquote>In this mode, dependency locking will still pin dynamic versions but otherwise changes to the dependency resolution are no longer errors.</blockquote><p>I encourage you to read more on the topic <a href="https://docs.gradle.org/current/userguide/dependency_locking.html">here</a>. Furthermore, I’d also like to know what workflows you guys come up with since this isn’t a very widely used feature of Gradle, and resources on the topic are minimal.<br>With that, our dependencies are fully managed with gradle.lockfile !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fcompleteblueandeancondor&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fcompleteblueandeancondor-teen-titant-go-titans-dance&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FCompleteBlueAndeancondor-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="640" height="368" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ac2d3b4ab1147577b0955eb9a34aa4/href">https://medium.com/media/e4ac2d3b4ab1147577b0955eb9a34aa4/href</a></iframe><h3>How Can You Contribute?</h3><ul><li>Connect with me on <a href="https://twitter.com/farazkhantweets">Twitter</a> or <a href="https://linkedin.com/in/frzkn">Linkedin</a> or <a href="https://github.com/frzkn">GitHub</a>.</li><li>Star the <a href="https://github.com/frzkn/LockAndroidGradleDeps">GitHub</a> repository.</li><li>Join me by following me as I will dive into interesting and lesser-known, and experience-driven aspects of React Native.</li><li>Lastly, share the article with your friends!</li><li><a href="https://docs.gradle.org/current/userguide/dependency_locking.html">Additional Learnings.</a></li></ul><p>If you liked this article, Show your support by <strong>clapping </strong>👏 on this article, do follow as I am planning to write more on not so talked about topics as a long-term React Native Developer. Your encouragement motivates me to write more and share insights that benefit the React Native community. Thank you for your support!</p><h3>Read My Other Blogs</h3><p><a href="https://medium.com/swlh/making-a-collapsible-sticky-header-animations-with-react-native-6ad7763875c3">Making a Collapsible Sticky Header — Animations With React Native</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0ff2eaacde2" width="1" height="1" alt=""><hr><p><a href="https://citymall.engineering/towards-reproducible-android-apps-locking-gradle-dependencies-c0ff2eaacde2">Towards Reproducible Android Apps — Locking Gradle Dependencies</a> was originally published in <a href="https://citymall.engineering/">CityMall Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Collapsible Sticky Header — Animations With React Native]]></title>
            <link>https://citymall.engineering/making-a-collapsible-sticky-header-animations-with-react-native-6ad7763875c3?source=rss-d3c6d3a81763------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad7763875c3</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[animated]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Faraz Khan]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 18:04:14 GMT</pubDate>
            <atom:updated>2023-07-21T12:31:40.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making a Collapsible Sticky Header — Animations With React Native</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gfSSD6rEFPZdPyQi6xv1A.png" /></figure><p>Recently I had to develop a collapsible or multi-layered sticky header in React Native for a project, I spent some time looking at how I would go about implementing, and at that time I would have preferred to have found a tutorial on achieving the same. Since I couldn’t find one as per my requirements. I decided to write a tutorial on the same.</p><h3>What we are building</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KLNIqm6n0BIbcVzUKx3lJA.gif" /></figure><p>The header hides and reveals based on the direction of the scroll and once the scrolling is stopped, the header conveniently snaps to the closest state i.e either half-hidden or fully revealed. This effect can be seen in apps like WhatsApp, Youtube, Telegram, etc. We’d be using React Native’s Animated API to build this so let’s get started!</p><p>I made a <a href="https://github.com/frzkn/rn-collapsible-header"><em>starter template</em></a><em> that</em> would save us some time by focusing on the topic of animations in this article. So I recommend you to clone the repository and follow along :)</p><h3>Instructions to setup the starter template</h3><ol><li>Clone the repository</li></ol><pre>git clone <a href="https://github.com/frzkn/rn-collapsible-header">https://github.com/frzkn/rn-collapsible-header</a></pre><p>2. Installing dependencies</p><pre>cd rn-collapsible-header &amp;&amp; yarn</pre><p>3. Switch to starter branch</p><pre>git checkout starter</pre><p>4. Starting the metro bundler</p><pre>yarn start</pre><p>4. Starting it on a device (Android in my case)</p><pre>yarn android</pre><blockquote>Note: This tutorial focuses on Android but its not much different to follow along for iOS.</blockquote><h3>Open up App.js &amp; see what’s already done for us</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e26720a4374a573b7c546015f709c5a/href">https://medium.com/media/1e26720a4374a573b7c546015f709c5a/href</a></iframe><p>App.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*gErlmszj7mNO8x4w8TE75A.png" /></figure><h3>Overview of what we’re going to do</h3><ol><li>Translating the header based on the scroll events</li><li>Implementing snap to <em>fully expanded</em> or <em>half expanded</em> state</li></ol><p>We have a FlatList which renders static data along with an app header. Upon scrolling, we can see that it doesn’t respond to our scroll events and just stays expanded. So let’s begin with that.</p><h3>Translating the header based on the scroll events</h3><p>I’ve broken down the following into 5 step process as follows,</p><p><strong>1. Converting our Components to Animated Components</strong></p><p>Currently, we are using FlatList which React native provides us with. To be able to use animations the <strong>Animation API </strong>requires us to wrap our components with an <strong>createAnimatedComponent</strong> function which applies all the animation properties to our normal component, Example below.</p><pre>const AnimatedFlatList = createAnimatedComponent(FlatList);</pre><p>For most commonly used components such as View, FlatList, etc. Animated API already provides us these components so we can start using these components directly instead. Firstly import Animated from react-native</p><pre>import {Animated, ... } from ‘react-native’</pre><p>Replace our FlatList with <strong>Animated.FlatList</strong> and the View which wraps the Header component with <strong>Animated.View</strong></p><p>Now, these components are ready to handle animations and animated events.</p><p><strong>2. Adding an onScroll Event</strong></p><p>The idea is to extract the progress of how much the user has scrolled in the Y direction. So to store this value, let’s create an animated value called scrollY</p><pre>const scrollY = useRef(new Animated.Value(0));</pre><p>FlatList takes an <strong>onScroll</strong> prop which is fired continuously as the FlatList is scrolled, we pass a function handle scroll which is an animated event. This animated event does one job to listen for changes in scrollY on the scroll and assign it to the scrollY variable.</p><pre>const handleScroll = Animated.event(<br>  [<br>    {<br>      nativeEvent: {<br>        contentOffset: {y: scrollY.current},<br>      },<br>    },<br>  ],<br>  {<br>    useNativeDriver: true,<br>  },<br>);</pre><p>Notice the <strong>useNativeDriver</strong> key, this is very important as that makes sure the Animation is running on the Native UI Thread and not blocking any Javascript operations. This is well explained in the <a href="https://reactnative.dev/blog/2017/02/14/using-native-driver-for-animated">blog on the react-native’s website</a>. But in a nutshell, it makes your animations achieve 60fps even on lower-end devices.</p><p>Now we’d get <strong>Value</strong> starting from 0 to the total height of the FlatList as the user scrolls. To clamp this value in a range, we’d use a function called diffClamp</p><p><strong>3. diffClamping our values</strong></p><p>As the name suggests the function does two things, Clamping the values between a range and returning a new value relative to the previous value. That means for a range of 0 to 10, Given the value x, we get 5 for the first time. It cannot be said that the subsequent calls with the same input will return the same output.</p><pre>const scrollYClamped = diffClamp(scrollY.current, 0, headerHeight);</pre><p>This will return us a value between the range of 0 to the height of the header which is 58 * 2. Lastly, we need to interpolate this value to a range of <strong>( -headerHeight / 2)</strong> i.e. half expanded state and <strong>0</strong> i.e. fully expanded state.</p><p><strong>4. Interpolating the value</strong></p><p>The idea is to translate the header in the negative Y direction as per the scroll position since we want to translate it up to the point of <strong>-( headerHeight/ 2)</strong> that is one of the output range along with <strong>0,</strong> which means the header is not translated at all.</p><p>Animated API provides us a convenient function called interpolate which takes an array of input range and output range and interpolates the input value to the output value. Pretty straight forward right?</p><pre>const translateY = scrollYClamped.interpolate({<br> inputRange: <strong>[0, headerHeight]</strong>,<br> outputRange: <strong>[0, -(headerHeight / 2)]</strong>,<br> });</pre><pre>const translateYNumber = useRef();</pre><pre>translateY.addListener(({value}) =&gt; {<br>  translateYNumber.current = value;<br>});</pre><p>We call it translateY as it will be the final calculated value required to drive our animation.</p><p>We also add a listener to this value as we’d be requiring the <strong>Animated.Value</strong> in the type of <strong>Number</strong> in the next part.</p><p><strong>5. Last piece of the puzzle</strong></p><p>Head down to <strong>Animated.View</strong> the wrapper we came across earlier and add the following style</p><pre>&lt;Animated.View style={[styles.header, {<strong>transform: [{translateY}]</strong>}]}&gt;<br> &lt;Header {…{headerHeight}} /&gt;<br> &lt;/Animated.View&gt;</pre><p>And that’s it, try scrolling and see the header smoothly react to scroll events. While it looks good but it is not perfect. from a usability point of view if the user stops scrolling while the header is <strong>between</strong> fully expanded and half expanded state. This becomes a bad UX as the user has to scroll more towards the downwards direction to fully reveal the contents of the first half of the header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-Y0p5TzaL00OdTTpHvmQVA.gif" /><figcaption>It doesn’t snap!</figcaption></figure><h3>Implementing snap to fully expanded or half expanded state</h3><p>Before diving into our approach I recommend you to see how other apps tackle this problem for yourself to have a better idea. Let’s take a look at a few together.</p><ul><li><strong>WhatsApp Messenger example</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dOi5jBkyMSsmgvJrhvlWRQ.gif" /><figcaption>Header slides down</figcaption></figure><p>We can see that for when the header is in between fully expanded and half expanded state the header and only header is snapped either to the top or bottom. This approach works but I went on to see more apps and how their approach to the problem</p><ul><li><strong>Telegram Messenger example</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*w5M52WLaFlV5Uh75wvasBA.gif" /><figcaption>FlatList Slides up</figcaption></figure><p>This one is pretty interesting as opposed to only animating the header, the FlatList is scrolled to either up or down for the header to reach to its two states.</p><p>I like this simplistic approach to the problem and react-native makes it easy to implement this as well. The idea is to see if the header is in semi-visible state, if so then scroll the FlatList enough so that the header gets in either of our two desired states. So let us implement that next</p><p><strong>Adding an onMomentumScrollEnd Event</strong></p><p>Unlike the onScroll event, the <strong>onMomemtumScrollEnd</strong> event only fires once the user stops scrolling. so let’s start by writing a handleSnap function and use the ref that is assigned to our FlatList.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/873a9231f27b96634b99165a0a6c3178/href">https://medium.com/media/873a9231f27b96634b99165a0a6c3178/href</a></iframe><pre>&lt;Animated.FlatList<br> scrollEventThrottle={16}<br> contentContainerStyle={{paddingTop: headerHeight}}<br> onScroll={handleScroll}<br> ref={ref}<br><strong> onMomentumScrollEnd={handleSnap}<br></strong> data={data}<br> renderItem={ListItem}<br> keyExtractor={(item, index) =&gt; `list-item-${index}-${item.color}`}<br> /&gt;</pre><p>This block is pretty self explanatory as well, the translateYNumber is the Animated.Value converted to the type Number. We use this value to check if the header is in the desired location, if not then we scroll the FlatList <strong>enough</strong> to make sure that the header snaps to the desired location.</p><blockquote><strong>Note</strong>: Theoritically we shouldn’t be needing to add an offsetY in the scrollToOffset method’s offset key but this seems to be bug where the offset is not applied automatically.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KLNIqm6n0BIbcVzUKx3lJA.gif" /></figure><p>And yay! our results are much better than before, it shows us something so simple can make or break the user experience. I am pretty happy with the results and that’s the end of it :)</p><h3>How Can You Contribute?</h3><ul><li>By making a PR on the <a href="https://github.com/frzkn/rn-collapsible-header">repository</a> as I know there are a lot better ways to do the same and would love to see your approaches.</li><li>Connect with me on <a href="https://twitter.com/farazkhantweets">Twitter</a> or <a href="https://linkedin.com/in/frzkn">Linkedin</a> or <a href="https://github.com/frzkn">GitHub</a>.</li><li>Star the <a href="https://github.com/frzkn/rn-collapsible-header">Github</a> repository.</li><li>Follow me for more related content.</li><li>Lastly share the article with your friends!</li></ul><p>If you liked this article, Show your support by <strong>clapping </strong>👏 on this article as this is my first article and that’d motivate me to write more often.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad7763875c3" width="1" height="1" alt=""><hr><p><a href="https://citymall.engineering/making-a-collapsible-sticky-header-animations-with-react-native-6ad7763875c3">Making a Collapsible Sticky Header — Animations With React Native</a> was originally published in <a href="https://citymall.engineering/">CityMall Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>