<?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 Moshfiqur Rahman Rony on Medium]]></title>
        <description><![CDATA[Stories by Moshfiqur Rahman Rony on Medium]]></description>
        <link>https://medium.com/@moshfiqrony?source=rss-69b37698dfa5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*8B_Q6bJlKGWp71TQPBFfmw.jpeg</url>
            <title>Stories by Moshfiqur Rahman Rony on Medium</title>
            <link>https://medium.com/@moshfiqrony?source=rss-69b37698dfa5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:52:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moshfiqrony/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[Make your commit more meaningful using emojis]]></title>
            <link>https://medium.com/@moshfiqrony/make-your-commit-more-meaningful-using-emojis-7dbf553293e8?source=rss-69b37698dfa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dbf553293e8</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[emoji-stories]]></category>
            <category><![CDATA[emoji]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Moshfiqur Rahman Rony]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 12:14:43 GMT</pubDate>
            <atom:updated>2020-07-30T12:14:43.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eC43SoQNVmbIb521pzQuOA.png" /></figure><p>Today I will show the emoji power in the commits. Commit is very powerful for a project. If you do not have meaningful commits then it is very hard for code reviewer and your co worker to work on or understand the changes.</p><p>To add emoji in your commit there are some ways.</p><ol><li>Use codes in your commit</li><li>Use extension in your VS Code</li></ol><h3>1. Use code in your commit</h3><p>There are some fixed codes for emojis that you can use in your commit. For example your commit is.</p><pre>git commit -m “Adding new package materialUi&quot;</pre><p>If you want to add an emoji in this commit then you can write your commit like this. <strong>:package:</strong> will add a package emoji in your commit.</p><pre>git commit -m &quot;:package: Adding new package materialUi&quot;</pre><h3>2. Use extension in your VS Code</h3><p>Here is a awesome VS Code extension that will allow you to add emoji in your commits from vs code —<a href="https://marketplace.visualstudio.com/items?itemName=Vtrois.gitmoji-vscode">Gitmoji</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pW1a6rQ-Qi0C81RQ.gif" /></figure><h3>This is the common and best emojis</h3><p><a href="https://gitmoji.carloscuesta.me/">https://gitmoji.carloscuesta.me/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RayJSvlgZ8V7pHSvaIhKXg.png" /><figcaption><a href="https://gitmoji.carloscuesta.me/">https://gitmoji.carloscuesta.me/</a></figcaption></figure><h3><strong>Here are all the possible emojis</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5157799dbf0e6f7e08830e379b4a081b/href">https://medium.com/media/5157799dbf0e6f7e08830e379b4a081b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dbf553293e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write multiple Axios mock implementations in testing.]]></title>
            <link>https://medium.com/@moshfiqrony/how-to-write-multiple-axios-mock-implementations-in-testing-78d3b5c6a8b5?source=rss-69b37698dfa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d3b5c6a8b5</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Moshfiqur Rahman Rony]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 16:22:54 GMT</pubDate>
            <atom:updated>2020-07-22T16:22:54.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Axios Mock Implementation Cover Image" src="https://cdn-images-1.medium.com/max/820/1*cBmoNNx8dE7SzR73RFIhww.png" /><figcaption>Axios Mock Implementation Cover Image</figcaption></figure><h3>Background Story</h3><p><a href="https://jestjs.io/"><strong>JEST</strong></a> and <a href="https://testing-library.com/docs/react-testing-library/intro"><strong>React Testing Library</strong></a> is now the most popular testing tool/framework for testing react components. Normally we do <a href="https://en.wikipedia.org/wiki/Unit_testing"><strong>Unit Testing</strong></a> or <a href="https://en.wikipedia.org/wiki/Integration_testing"><strong>Integration Testing</strong></a> using these tools. If you set up your react project custom then you can use it by installing JEST and React Testing Library using <a href="https://www.npmjs.com/">NPM</a> or <a href="https://yarnpkg.com/">Yarn</a>. You can also use <a href="https://github.com/facebook/create-react-app">Create-React-App</a> to create your app.</p><h3>Topic</h3><p><a href="https://github.com/axios/axios"><strong>Axios</strong></a> is a very well Promise based HTTP client for the browser and node.js. It helps to make an HTTP request to the API endpoint. When we use axios in our front end code it is a bit tricky to test the code. It also became very tricky if it is inside any life cycle methods like <a href="https://reactjs.org/docs/hooks-effect.html"><strong>useEffect</strong></a> or <a href="https://reactjs.org/docs/react-component.html#componentdidmount"><strong>componentDidMount</strong></a><strong>.</strong> As you come for the blog I am assuming you have an idea about <a href="https://reactjs.org/">React</a> and life cycle methods.</p><h3>The problem in testing with Axios</h3><p>When we test an app we should not call the real API. It is not a best practice to call the real API in testing. Because we might need to test a software after deploying the app. So if we make unwanted API call in a deployed app it will create data mess in your API backend or database. So we have to create a fake axios which we call Mock in testing. At the time of testing, you can Mock any of your imported functions or package.</p><h3>What is our approach to solve the problem</h3><p>To solve the problem we have to create a fake axios implementation, to do that we need to understand the implementation of the real axios package. we use axios by importing like bellow in our code</p><pre>import axios from &#39;axios&#39;;</pre><p>after that we use some function from axios like get, post, put, delete, etc. suppose we will use get. We will write like bellow</p><pre>axios.get(&#39;apiEndpoint&#39;)</pre><p>this function returns a promise. we are not going deep in promise just for understanding if any function returns a promise then we can write like bellow</p><pre>axios.get(&#39;api&#39;)<br>.then(response =&gt; {</pre><pre>    //do some stuff here.<br>})</pre><p>So we have to design something that has the same facility and ability. so let’s solve it.</p><h3>Solve</h3><blockquote>At first we will create fake axios</blockquote><p>to do that at first create a folder named as <strong>__mock__. </strong>What it for — whatever you will give inside this folder jest will automatically understand that it is mocked by the user. We will be more clear when er will use it in code later on. now create a file named <strong>axios.js </strong>and write the code below. This is basic js code we are creating a module export and inside the that we have an entry which is <strong>get</strong> and it is a jest function. <em>jest.fn() </em>it is from JEST so we do not need to think about it. This jest function can have an implementation function. In our case, our function returns a Promise and the promise returns the same data that a get returns from axios call. We do not need to worry about the function because we have the ability to re-implement the function.</p><pre>module.exports = {<br>    get: jest.fn(<br>        () =&gt; Promise.resolve(<br>            {<br>                data: {}, <br>                status: 300<br>            }<br>            )<br>        )<br>}</pre><p>now our axios is ready and we just need to use it.</p><blockquote>Let’s create a test</blockquote><p>At first, we will import what we need. Here axios we import will automatically import the mock axios as we have a <strong>__mock__ </strong>folder and <em>axios.js</em> inside it, we took a describe block inside it we took a test block and inside it we re-implemented the get of from axios using <strong>mockImplementationOnce </strong>function like bellow. Here we can return what expected data we want from the API call.</p><pre>import axios from &#39;axios&#39;<br>import React from &#39;react&#39;<br>import { render, waitFor } from &#39;<a href="http://twitter.com/testing">@testing</a>-library/react&#39;;</pre><pre>describe(&#39;API Call axios mock testing&#39;, () =&gt; {</pre><pre>test(&#39;Component rendered successfully&#39;, async () =&gt; {<br>        axios.get.mockImplementationOnce(() =&gt; Promise.resolve({<br>            status: 200,<br>            data: {<br>                name: &#39;Rony&#39;,<br>                email: &#39;<a href="/service/mailto:rony@getd2.com">rony@example.com</a>&#39;<br>            }<br>        }))<br>    })<br>})</pre><p>now if we want to make multiple implementations of the axios get then we can write like bellow</p><pre>describe(&#39;API Call axios mock testing&#39;, () =&gt; {</pre><pre>test(&#39;Component rendered successfully&#39;, async () =&gt; {<br>        axios.get<br>        .mockImplementationOnce(() =&gt; Promise.resolve({<br>            status: 200,<br>            data: {<br>                name: &#39;Rony&#39;,<br>                email: &#39;<a href="/service/mailto:rony@example.com">rony@example.com</a>&#39;<br>            }<br>        }))<br>        .mockImplementationOnce(() =&gt; Promise.resolve({<br>            status: 202,<br>            data: {<br>                name: &#39;Rony&#39;,<br>                email: &#39;<a href="/service/mailto:rony@mock.com">rony@mock.com</a>&#39;<br>            }<br>        }))<br>        .mockImplementationOnce(() =&gt; Promise.resolve({<br>            status: 400,<br>            data: null<br>        }))<br>        <br>    })<br>})</pre><p>what we did is we wrote three <strong>mockImplementationOnce </strong>for our get. So in our code, if the <strong>axios.get()</strong> is called the first time, it will return whatever we defined in the first <strong>mockImplementationOnce </strong>block. For the second <strong>axios.get() </strong>call it it will return whatever we defined in the first <strong>mockImplementationOnce </strong>block. That’s how, as many new implementations we will define it will return that according to the calling. Suppose in your code <strong>axios.get() </strong>is called 6 times then, for the first three calls it will return whatever we defined in the <strong>mockImplementationOnce,</strong> and then as we have no other new implementations then it will return the default return in the fake axios.js file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d3b5c6a8b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MutationObserver or regeneratorRuntime error solve in testing using JEST and react-testing-library]]></title>
            <link>https://medium.com/@moshfiqrony/mutationobserver-or-regeneratorruntime-error-solve-in-testing-using-jest-and-react-testing-library-495cfbff6400?source=rss-69b37698dfa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/495cfbff6400</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-testing]]></category>
            <dc:creator><![CDATA[Moshfiqur Rahman Rony]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 13:25:18 GMT</pubDate>
            <atom:updated>2020-07-11T08:53:25.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="courtesy : freecodecamp" src="https://cdn-images-1.medium.com/max/1000/1*sv-LTdcuXGM0O37yUAbPSw.png" /><figcaption>Cover Photo Courtesy: freecodecamp</figcaption></figure><h3>Background Story</h3><p><a href="https://jestjs.io/"><strong>JEST</strong></a> and <a href="https://testing-library.com/docs/react-testing-library/intro"><strong>React Testing Library</strong></a> is now the most popular testing tool/framework for testing react components. Normally we do <a href="https://en.wikipedia.org/wiki/Unit_testing"><strong>Unit Testing</strong></a> or <a href="https://en.wikipedia.org/wiki/Integration_testing"><strong>Integration Testing</strong></a> using these tools. If you set up your react project custom then you can use it by installing JEST and React Testing Library using <a href="https://www.npmjs.com/">NPM</a> or <a href="https://yarnpkg.com/">Yarn</a>. You can also use <a href="https://github.com/facebook/create-react-app">Create-React-App</a> to create your app.</p><h3>How the errors look like</h3><blockquote>ReferenceError: regeneratorRuntime is not defined</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*aSxhESLZ5fSQ6o2a5YwVKQ.png" /><figcaption>regeneratorRuntime error screenshot</figcaption></figure><blockquote>TypeError: MutationObserver is not a constructor</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*nfdXkt_hsgNk2a-70U1jbA.png" /><figcaption>MutationObserver error screenshot</figcaption></figure><p>both of the errors may come for using <strong>async </strong>or making the test <strong>async</strong>.</p><h3>How an async test look like</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef8a64794acc857aa7c8dc5a67e0ea01/href">https://medium.com/media/ef8a64794acc857aa7c8dc5a67e0ea01/href</a></iframe><h3>Real Problem</h3><p>If you know much about testing then you should know they use <a href="https://github.com/jsdom/jsdom">JSDOM</a> to render the component at the time of testing a component. So some keywords like <strong>import, async, await</strong> these are not recognizable by the DOM or the testing environment. So the error you got is a much more keyword issue. Actually, it is not recognizing or it cannot be able to use the keywords in this context.</p><h3>Solve</h3><blockquote>At first install <strong>jest-environment-jsdom-sixteen</strong></blockquote><pre>yarn add --dev jest-environment-jsdom-sixteen</pre><blockquote>Then edit your scripts in <strong>package.json</strong> file</blockquote><pre>&quot;scripts&quot;: {</pre><pre>&quot;test&quot;: &quot;jest --env=jest-environment-jsdom-sixteen --watch&quot;</pre><pre>}</pre><blockquote>Now install <strong>core-js</strong> and <strong>regenerator-runtime</strong></blockquote><pre>yarn add --dev regenerator-runtime</pre><pre>yarn add --dev core-js</pre><p>Now create <strong>setupTest.js</strong> file in your root directory and write the following code</p><pre>import &#39;regenerator-runtime/runtime&#39;</pre><pre>import &#39;core-js/stable&#39;</pre><blockquote>Now edit and create a <strong>JEST</strong> entry in your <strong>package.json</strong> like bellow</blockquote><pre>&quot;jest&quot;:{</pre><pre>&quot;setupFilesAfterEnv&quot;:[&quot;./setupTests.js&quot;]</pre><pre>}</pre><p>your <strong>package.json </strong>file should look like bellow. Ignore the <strong>dependency</strong> or <strong>devDependency</strong> I installed, just follow the architecture for jest entry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5201216b57e4f51742859f5019beef/href">https://medium.com/media/fd5201216b57e4f51742859f5019beef/href</a></iframe><blockquote>Now run your test command and it should work fine</blockquote><pre>yarn test </pre><p>Thank you so much for reading the article. Feel free to share it and comment if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495cfbff6400" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use React Native and Android Native Merged Boilerplate]]></title>
            <link>https://medium.com/@moshfiqrony/react-native-and-android-native-boiler-plate-72a08409feed?source=rss-69b37698dfa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a08409feed</guid>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[boilerplate]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Moshfiqur Rahman Rony]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 12:25:20 GMT</pubDate>
            <atom:updated>2019-11-18T15:49:29.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*JtlAMaY4YxJcqRd5YPW04Q.jpeg" /><figcaption>Credit — futuremind</figcaption></figure><p>In this<strong> </strong><a href="https://github.com/moshfiqrony/react-native-android-native-mergerd-boilerplate"><strong>repository</strong></a><strong>,</strong> you can have a React Native app and a basic Android app. Using this repo you can add multiple android native intent or activity to your react native app. just simply open the android folder with your android studio and use the folder as your android native app and the root as your react native app</p><p>Github Repository link - <a href="https://github.com/moshfiqrony/react-native-android-native-mergerd-boilerplate">https://github.com/moshfiqrony/react-native-android-native-mergerd-boilerplate</a></p><h3>Pre Environment or setup</h3><ol><li><a href="https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html"><strong>JDK 1.8</strong></a><strong> </strong>or higher</li><li><strong>JAVA_HOME</strong> path set up correctly.</li><li><a href="https://developer.android.com/studio"><strong>Android Studio</strong></a> installed and running.</li></ol><ul><li>for all kinds of environment edit like adding the path and installing node, restart your ide.</li></ul><h3>How to use the repo?</h3><ol><li>Simply clone the repo or download it.</li><li>Open the android folder with <a href="https://developer.android.com/studio">Android Studio</a></li><li>Open the root folder with any IDE like <a href="https://code.visualstudio.com/"><strong>Visual Code</strong></a><strong>, </strong><a href="https://www.jetbrains.com/pycharm/"><strong>Pycharm</strong></a><strong>, </strong><a href="https://www.jetbrains.com/webstorm/"><strong>WebStorm</strong></a><strong>,</strong></li><li>run npm install or yarn install from the root of the repo.</li><li>Now run react-native run-android then run react-native start if you get any error like <strong>debug.keystore</strong> not found or SDK dir not found then.</li><li>Create <strong>local.properties</strong> file inside the android folder and write</li></ol><blockquote>sdk.dir = your sdk dir</blockquote><p>7. run this command</p><blockquote>keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000</blockquote><p>for debug.keystore if needed and move it to app folder under the android folder</p><p>8. Finally, run react-native run-android</p><p>9. And run react-native start</p><p>10. if react-native start is giving Invalid regular expression invalid error check <strong>node.js</strong> version and install version <strong>10</strong></p><p>11. if <strong>ADB</strong> is not found then add the path &lt;YOUR_SDK_LOCATION&gt;\platform-tools in environment variables</p><h3>How to add Android Native Activity</h3><ol><li>Open the android folder with <a href="https://developer.android.com/studio"><strong>Android Studio</strong></a></li><li>Now create an empty activity eg. My one I named as <strong>BasicModule</strong></li><li>Now Extend <strong>ReactContextBaseJavaModule</strong> override and rearrange it all the required methods like bellow</li></ol><pre>public class BasicModule extends ReactContextBaseJavaModule {</pre><pre>    ReactApplicationContext context = getReactApplicationContext();</pre><pre>    public BasicModule(@Nonnull ReactApplicationContext reactContext) {<br>        super(reactContext);<br>    }</pre><pre>    @Nonnull<br>    @Override<br>    public String getName() {<br>        return &quot;MyModule&quot;;<br>    }<br></pre><pre>    @ReactMethod<br>    public void NavigateMe(){<br>        Intent intent = new Intent(context, NavigationDrawerActivity.class);<br>        if(intent.resolveActivity(context.getPackageManager()) != null){<br>            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br>            context.startActivity(intent);<br>        }<br>    }<br>}</pre><p>Your activity is now having a NavigationDrawer you can do whatever you need.</p><p>4. Now goto <strong>MyModulePackage.java</strong> and add your activity like this bellow</p><pre>modules.add(new BasicModule(reactContext));</pre><p>Full code is here</p><pre>public class MyModulePackage implements ReactPackage {<br>    @Nonnull<br>    @Override<br>    public List&lt;NativeModule&gt; createNativeModules(@Nonnull ReactApplicationContext reactContext) {<br>        List &lt;NativeModule&gt; modules = new ArrayList();<br>        modules.add(new BasicModule(reactContext));<br>        //add more here<br>        return modules;<br>    }</pre><pre>    @Nonnull<br>    @Override<br>    public List&lt;ViewManager&gt; createViewManagers(@Nonnull ReactApplicationContext reactContext) {<br>        return Collections.emptyList();<br>    }<br>}</pre><p>In this way add how many activities you need.</p><h3>How to use it in React Native</h3><ol><li>Import <strong>NativeModules</strong></li></ol><pre>import {StyleSheet, View, Text, Button, NativeModules} from &#39;react-native&#39;;</pre><p>2. Use it like</p><pre>NativeModules.MyModule.NavigateMe();</pre><p>here NavigateMe() is the @ReactMethod that we defined in our activity <strong>BasicModule</strong></p><p>Now whenever the code will call the function NavigateMe() it will activate the android native activity <strong>BasicModule</strong></p><p>Happy Coding</p><p>Github Repository link — <a href="https://github.com/moshfiqrony/react-native-android-native-mergerd-boilerplate">https://github.com/moshfiqrony/react-native-android-native-mergerd-boilerplate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a08409feed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Enable OnBackPress Exit Facility In Your React Native App]]></title>
            <link>https://medium.com/@moshfiqrony/how-to-enable-onbackpress-exit-facility-in-your-react-native-app-37880c4d3b4e?source=rss-69b37698dfa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/37880c4d3b4e</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-router-flux]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Moshfiqur Rahman Rony]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 11:05:20 GMT</pubDate>
            <atom:updated>2019-04-21T12:21:22.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeYkbTYeJFf1mr2kje4PYg.jpeg" /></figure><p>How does <strong>Back Pressed</strong> worked in React Native:</p><p>To achieve Back Pressed worked in react native we need to follow some conventions. As because RN is a hybrid app we cannot achieve this facility of Android directly. So we just need to follow some steps and conventions that will allow us to get the facility of android.</p><p><strong>Step 1:</strong> At first we need to import <strong>BackHandler</strong> module from ‘<strong>react-native</strong>’ library. This module will allow the RN to communicate with the core hardware of Android.</p><pre><strong>import {BackHandler} from “react-native”;</strong></pre><p><strong>Step 2:</strong> Then we need to define a back handler method/function where we will write the Back Pressed event action</p><pre><strong>handleBackButton</strong>(){<br>}</pre><p><strong>Step 3: </strong>Now we need to add and bind this function to our <strong>BackHandler </strong>module in componentDidMount method at the time of component loading, to do that we need to use <strong>addEventListener </strong>method of<strong> BackHandler </strong>module and add the<strong> handleBackButton </strong>method to<strong> BackHandler </strong>and bind it with the scope of that class.</p><pre><strong>BackHandler.addEventListener(‘hardwareBackPress’,this.handleBackButton.bind(this));</strong></pre><p><strong>Step 4: </strong>Now we ready to make our handleBackButton work. So to exit in back button pressed in your android device. We need to write</p><pre><strong>BackHandler.exitApp();</strong></pre><blockquote><strong>Full code</strong></blockquote><pre><strong>import</strong> React, {Component} <strong>from</strong> &#39;react&#39;;<br><strong>import</strong> {Actions, Router, Scene} <strong>from</strong> &quot;react-native-router-flux&quot;;<br><strong>import</strong> Login <strong>from</strong> &quot;./src/login&quot;;<br><strong>import</strong> {BackHandler} <strong>from</strong> &quot;react-native&quot;;<br><br><strong>export</strong> <strong>default</strong> <strong>class</strong> <strong>App</strong> <strong>extends</strong> <strong>Component</strong>&lt;<strong>Props</strong>&gt; {<br>   componentDidMount() {<br>       BackHandler.addEventListener(&#39;hardwareBackPress&#39;, <strong>this</strong>.handleBackButton.bind(<strong>this</strong>));<br>   }<br>   handleBackButton(){<br>             BackHandler.exitApp();<br>         }<br><br>   render() {<br>       <strong>return</strong> (<br>           &lt;<strong>Router</strong>&gt;<br>               &lt;<strong>Scene</strong> key=&#39;root&#39;&gt;<br>                   &lt;<strong>Scene</strong><br>                       key=&quot;login&quot;<br>                       hideNavBar<br>                       component={Login}<br>                   /&gt;<br>                &lt;/<strong>Scene</strong>&gt;<br>           &lt;/<strong>Router</strong>&gt;<br>       );<br>   }<br>}</pre><p><strong>Step 5: </strong>Now we can make it a little bit smarter. If this code is working for you then you can try next this. So now we will make our onbackPressExit 1 step ahead. As we are using react-native-router-flux that’s mean we are using Router and Scene. So we have several Scenes here. So if the user presses back on any screen then the app will exit. So what if we want to exit in a specific Scene. So to do so we have to conditionally execute the BackHandler.exitApp() command. Here is the code, at the end of the code I will explain what is going on.</p><blockquote><strong>Full Modified Code</strong></blockquote><pre><strong>import</strong> React, {Component} <strong>from</strong> &#39;react&#39;;<br><strong>import</strong> {Actions, Router, Scene} <strong>from</strong> &quot;react-native-router-flux&quot;;<br><strong>import</strong> Login <strong>from</strong> &quot;./src/login&quot;;<br><strong>import</strong> Login2 <strong>from</strong> &quot;./src/dashboard&quot;;<br><strong>import</strong> MoreScreen <strong>from</strong> &#39;./src/MoreScreen&#39;;<br><strong>import</strong> {BackHandler, ToastAndroid} <strong>from</strong> &quot;react-native&quot;;<br><strong>import</strong> Campaigns <strong>from</strong> &quot;./src/campaign&quot;;<br><strong>import</strong> Agents <strong>from</strong> &#39;./src/agents&#39;;<br><br>let backPressed = 0;<br><br><strong>export</strong> <strong>default</strong> <strong>class</strong> <strong>App</strong> <strong>extends</strong> <strong>Component</strong>&lt;<strong>Props</strong>&gt; {<br>   componentDidMount() {<br>       BackHandler.addEventListener(&#39;hardwareBackPress&#39;, <strong>this</strong>.handleBackButton.bind(<strong>this</strong>));<br>   }<br><br>   constructor(){<br>       <strong>super</strong>();<br>       <strong>this</strong>.state={<br>           isloggedin: false,<br>           backPressed: 1<br>       }<br>   }<br><br>   handleBackButton(){<br>       <strong>if</strong>(Actions.currentScene === &#39;campaigns&#39; || Actions.currentScene === &#39;agents&#39; || Actions.currentScene === &#39;dashboard&#39;){<br>           <strong>if</strong>(backPressed &gt; 0){<br>               BackHandler.exitApp();<br>               backPressed = 0;<br>           }<strong>else</strong> {<br>               backPressed++;<br>               ToastAndroid.show(&quot;Press Again To Exit&quot;, ToastAndroid.SHORT);<br>               setTimeout( () =&gt; { backPressed = 0}, 2000);<br>               <strong>return</strong> true;<br>           }<br>       }<br>   }<br><br>   render() {<br>       <strong>return</strong> (<br>           &lt;Router&gt;<br>               &lt;Scene key=&#39;root&#39;&gt;<br>                   &lt;Scene<br>                       key=&quot;login&quot;<br>                       hideNavBar<br>                       component={Login}<br><br>                   /&gt;<br>                   &lt;Scene<br>                       key=&#39;dashboard&#39;<br>                       hideNavBar<br>                       component={Login2}<br>                       title={&#39;Dashboard&#39;}<br><br>                   /&gt;<br>                   &lt;Scene<br>                       key=&#39;MoreScreen&#39;<br>                       hideNavBar<br>                       component={MoreScreen}<br>                       title={&#39;MoreScreen&#39;}<br>                   /&gt;<br>                   &lt;Scene<br>                       key=&#39;campaigns&#39;<br>                       hideNavBar<br>                       component={Campaigns}<br>                       title={&#39;campaigns&#39;}<br>                   /&gt;<br>                   &lt;Scene<br>                       key=&#39;agents&#39;<br>                       hideNavBar<br>                       component={Agents}<br>                       title={&#39;agents&#39;}<br>                   /&gt;<br><br>               &lt;/Scene&gt;<br>           &lt;/Router&gt;<br>       );<br>   }<br>}</pre><p>Here in the render, we have a return function under the return function we have a Route component and under Route, we have a root Scene, under the route Scene we have 5 Scenes. These five scenes are</p><pre>&lt;<strong>Scene</strong><br>   key=&quot;login&quot;<br>   hideNavBar<br>   component={Login}<br><br>/&gt;</pre><pre>&lt;<strong>Scene</strong><br>   key=&#39;dashboard&#39;<br>   hideNavBar<br>   component={Login2}<br>   title={&#39;Dashboard&#39;}<br><br>/&gt;</pre><pre>&lt;<strong>Scene</strong><br>   key=&#39;MoreScreen&#39;<br>   hideNavBar<br>   component={MoreScreen}<br>   title={&#39;MoreScreen&#39;}<br>/&gt;</pre><pre>&lt;<strong>Scene</strong><br>   key=&#39;campaigns&#39;<br>   hideNavBar<br>   component={Campaigns}<br>   title={&#39;campaigns&#39;}<br>/&gt;</pre><pre>&lt;<strong>Scene</strong><br>   key=&#39;agents&#39;<br>   hideNavBar<br>   component={Agents}<br>   title={&#39;agents&#39;}<br>/&gt;</pre><p>Now if we want that only if the user is in Dashboard, Agents or Campaign only then the Back Press button will exit the app. So to achieve the productivity we need to update the <strong>handleBackButton </strong>Method in the following way.</p><pre>handleBackButton(){<br>   <strong>if</strong>(Actions.currentScene === &#39;campaigns&#39; || Actions.currentScene === &#39;agents&#39; || Actions.currentScene === &#39;dashboard&#39;){<br>       <strong>if</strong>(backPressed &gt; 0){<br>           BackHandler.exitApp();<br>           backPressed = 0;<br>       }<strong>else</strong> {<br>           backPressed++;<br>           ToastAndroid.show(&quot;Press Again To Exit&quot;, ToastAndroid.SHORT);<br>           setTimeout( () =&gt; { backPressed = 0}, 2000);<br>           <strong>return</strong> true;<br>       }<br>   }<br>}</pre><p>Here one thing we also did that is press again toast. So if the user is in the desired Scene and press back button then a toast will appear that will tell the user to press one more time the back button to exit. To Achieve the facility we used <strong>ToastAndroid </strong>module of <strong>react-native. </strong>We also declare a variable named backPressed at the top as a global variable and signed 0 to it.</p><pre><strong>let </strong>backPressed = 0;</pre><p>This variable is used to keep track, how many times the user has pressed the back button. so in the <strong>handleBackButton</strong> method we checked that if the user is in right Scene by the condition of</p><pre><strong>if</strong>(Actions.currentScene === &#39;campaigns&#39; || Actions.currentScene === &#39;agents&#39; || Actions.currentScene === &#39;dashboard&#39;)</pre><p>and then we checked how many times the button pressed.</p><pre><strong>if</strong>(backPressed &gt; 0)</pre><p>If it is more than 1 time then the true part of the <strong>IF</strong> body will execute and the app will exit.</p><pre>{<br>    BackHandler.exitApp();<br>    backPressed = 0;<br>}</pre><p>but if it is the first time the back button is pressed then the backPressed variable will be incremented and the Toast will be shown.</p><pre>backPressed++;<br><strong>ToastAndroid</strong>.show(<strong>&quot;Press Again To Exit&quot;</strong>, <strong>ToastAndroid</strong>.<strong>SHORT</strong>);</pre><p>Next on I also moved the functionality to a more bit further. So to solve a bug(if you press the button once and go to other Scene and then press the back button again it will exit. Not showing a toast of showing that “press again to exit”).</p><p>to solve this bug we used a function setTimeout where we waited 2 seconds. within this 2 second if the second back pressed button not pressed then the backPressed variable will be reset to 0 so that the user goes to another scene and press back again then it again shows the toast and returns true so that it does not execute the default back press event.</p><pre><em>setTimeout</em>( () =&gt; { backPressed = 0}, 2000);<br><strong>return true</strong>;</pre><p>That’s how the app will only be exited if the user is in the dashboard, agents, or in the scene of the campaign. Otherwise, the back press button will work default</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37880c4d3b4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>