<?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 Milind Patil on Medium]]></title>
        <description><![CDATA[Stories by Milind Patil on Medium]]></description>
        <link>https://medium.com/@milind.patil?source=rss-76aeacd37e36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mU7iUeNXdiXKfnSSju-6Cg.jpeg</url>
            <title>Stories by Milind Patil on Medium</title>
            <link>https://medium.com/@milind.patil?source=rss-76aeacd37e36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:24:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milind.patil/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[Improving React-Native App’s Performance]]></title>
            <link>https://medium.com/@milind.patil/improving-react-native-apps-performance-4a72ae69c5a9?source=rss-76aeacd37e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a72ae69c5a9</guid>
            <dc:creator><![CDATA[Milind Patil]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 05:53:07 GMT</pubDate>
            <atom:updated>2022-04-12T07:03:08.915Z</atom:updated>
            <content:encoded><![CDATA[<p>React-Native apps suffer huge performance issues as compared to native apps. So, let’s have a closer look on performance improvements for your React Native app during its development. To improve your React Native application performance, here are some common practices, which will help you a lot during the development of a complex project.</p><h3><strong>1. Memory leakage in Android lists:</strong></h3><blockquote>Avoid use of ScrollView and use FlatList or SectionList to render huge lists</blockquote><p>If you have a large list, rendering all the items at once can cause a performance issue, but lazy loading with FlatList can improve performance. The FlatList component renders only the items that will be displayed on the screen and removes them when they are no longer displayed. This saves a lot of memory, making the application much faster.</p><h3><strong>2. Avoid Passing Inline Functions as Props:</strong></h3><blockquote>When passing a function as a property to a component, avoid passing that function inline, like below:</blockquote><pre><em>function HandleEventComponent(props) {<br>return(<br>&lt;Button title=‘Click here‘ onPress={props.onPress}/&gt;<br>)<br>}<br>export default function EventPerformer() {<br>return (<br>&lt;View style={styles.container}&gt;<br>&lt;HandleEventComponent<br>onPress={()=&gt; console.log(‘Handling an event ’)}<br>/&gt;<br>&lt;/View&gt;<br>);<br>}</em></pre><p>To improve react-native performance, we recommended programmers to avoid the above method as it recreates functions whenever a new reference gets rendered by the parent. Here child components get re-rendered automatically even if master props remain the same. <br>The solution is to declare the function inside a class format or within a function to eliminate the chances of re-renders.</p><pre><em>export default function EventPerformer() {<br>function handleEvent(){<br>console.log(‘Handling an event, please wait!’)<br>}<br>return (<br>&lt;View style={styles.container}&gt;<br>&lt;HandleEventComponent<br>onPress={handleEvent}<br>/&gt;<br>&lt;/View&gt;<br>);<br>}</em></pre><h3><strong>3. Provide Appropriate Navigation Strategies:</strong></h3><blockquote>React Native offers four different ways to build navigation:</blockquote><p><strong>iOS Navigator</strong>: Navigator-iOS was designed as native for IOS. <br><strong>Navigator: </strong>It can be used only for small applications but not suitable for complex apps. <br>Navigation Experiment:NavigationExperimental was designed as a highly configurable navigator but due to its complexity it was more confusing for most developers to understand and grasp. <br>React Navigation: A better solution for navigation in react native. It is recommended to use React Navigation for all — small, large, complex apps.</p><h3><strong>4. Eliminate Console Statements:</strong></h3><p>Console statements should be removed before bundling as they can create some critical performance issues with React Native platform.<br>If you don’t want these statements to mess with the JS thread, you must run a third-party react-native app optimization tool i.e., <strong>babel-plugin-transform-remove-console </strong>which is a preferred plugin to remove console statements. You can simply use the following commands to install this plugin:<br><strong><em>npm install babel-plugin-transform-remove-console</em></strong> <br>or <br><strong><em>yarn add babel-plugin-transform-remove-console</em></strong></p><pre><em>{<br>post-app<br>“env”: {<br>“production”: <br>{<br>“plugins”: [“transform-remove-console”]<br>}<br>}<br>}</em></pre><h3><strong>5. React Native Image Optimization:</strong></h3><p>It is important to optimize images to improve your React Native app’s performance. Rendering multiple images could lead to high memory usage on a device if the images are not appropriately optimized in terms of resolution and size. This may cause your app to crash due to memory overload. <br>To avoid facing app crashes or laggy performance, we can apply following techniques, which in turn optimize images in a React Native app: <br>- Using smaller-resolution images <br>- Using images in PNG format, not in JPG <br>- Using WEBP format for images — this can help reduce the images’ binary size on iOS and Android by 30% (approx.) of the original size.</p><h3><strong>6. Image caching:</strong></h3><p>Caching is a way to deal with image problems that further optimizes the overall performance of your react native application. However, you need save the images locally the first time they are loaded and uses the local cache in the subsequent requests. This could improve the app performance remarkably. But caching with the image component is supported in iOS alone, not in Android. <br>Here’s how you would cache an image:</p><pre><em>&lt;Image<br>source={{<br>uri: ‘</em><a href="https://picsum.photos/200/300"><em>https://picsum.photos/200/300</em></a><em>&#39;<br>cache: ‘only-if-cached’<br>}<br>}<br>style={{ … }}<br>/&gt;</em></pre><p>While loading Image in react-native there are several issues such as: <br>- Image flickering <br>- Rendering a huge number of images on a single screen <br>- Low performance in cache loading <br>- Low app performance<br>These issues can be easily resolved by using third-party libraries, like react-native-fast-image<br>In addition to caching images, Fast Image component also adds authorisation headers and several other features.</p><pre><em>import FastImage from ‘react-native-fast-image’<br>const App = () =&gt; (<br>&lt;FastImage<br>style={{ … }}<br>source={{<br>uri: ‘</em><a href="https://picsum.photos/200/300"><em>https://picsum.photos/200/300</em></a><em>&#39;,<br>headers: { Authorization: ‘auth-token’ },<br>priority: FastImage.priority.normal,<br>}<br>}<br>resizeMode={FastImage.resizeMode.contain}<br>/&gt;<br>)</em></pre><p>One can also use some other libraries such as the react-native-cached-image to cache and load images. Here’s how to use it.</p><pre><em>import { CachedImage } from ‘react-native-cached-image’;<br>&lt;CachedImage<br>style={{ … }}<br>source={{ uri: item.urls.raw }}<br>/&gt;</em></pre><h3><strong>7. Make Use of Hermes:</strong></h3><p>Hermes is an open-source JavaScript engine optimized specifically for mobile applications. It is available for the Android platform for React Native version <strong>0.60.4</strong> and above. It is also available for iOS from version <strong>0.64-rc.0</strong> and above. Hermes helps reduce the download size of the APK, the memory footprint and consumption, and the time needed for the app to become interactive (TTI — Time to Interact).</p><p>To enable Hermes for Android, open build.gradle and add the following line:<br><strong>def enableHermes = project.ext.react.get(“enableHermes”, true);</strong></p><p>To enable Hermes for iOS, open Podfile and add the following line:<br><strong>use_react_native!(:path =&gt; config[:reactNativePath], :hermes_enabled =&gt; true</strong></p><h3><strong>8. Avoid Expensive &amp; Unreasonable Renders:</strong></h3><p>React introduced the memo HOC (Higher Order Component) in React 16.6 for preventing unnecessary re-rendering and the useMemo hook in React 16.8 for optimizing expensive computations.<br>However, it is also possible to use the useCallback hook to do that. The major difference between useMemo and useCallback is that useMemo returns a memoized value but useCallback returns a memoized callback.</p><p>Let’s take a look at each of them:</p><ul><li><strong>The React.memo Higher Order Component (HOC)</strong> <br><strong> </strong>React.memo was introduced to functional components to serve the same purpose the React PureComponents serves in class components. memo prevents unnecessary re-rendering of a component and could help to optimize an application.</li></ul><p>However, like other optimization techniques, memo should only be used when it is necessary. In some cases, unnecessary re-rendering would not impact so much on performance.</p><blockquote>Here is an example to illustrate memo.</blockquote><pre><em>import React from ‘react’<br>import {View, Text, TouchableOpacity} from ‘react-native’<br>const Element = ({children, value, setValue}) =&gt;{<br>const handleOperation = () =&gt; setValue(value * 2)<br>return (<br>&lt;View&gt;<br>&lt;Text&gt;{value}&lt;/Text&gt;<br>&lt;TouchableOpacity onPress={handleOperation}&gt;<br>{children}<br>&lt;/TouchableOpacity&gt;<br>&lt;/View&gt;<br>)<br>}<br>export default Element</em></pre><pre><em>import React, {useState} from ‘react’<br>import {View} from ‘react-native’<br>import Element from ‘./Element’<br>const App = () =&gt;{<br>const [firstNum, setFirstNum] = useState(5)<br>const [secondNum, setSecondNum] = useState(5)<br>return(<br>&lt;View&gt;<br>&lt;Element setValue={setFirstNum} value={firstNum} &gt; Add First &lt;/Element&gt;<br>&lt;Element setValue={setSecondNum} value={secondNum} &gt; Add Second &lt;/Element&gt;<br>&lt;/View&gt;<br>)<br>}</em></pre><p>The problem with the above code is that when any of the buttons are pressed, both buttons will re-render even though only the states for the pressed button will be changed.</p><p>This can be fixed by wrapping the Element component with the React.memo HOC. Here’s how to do that.</p><pre><em>import React, {memo} from ‘react’<br>import {View, Text, TouchableOpacity} from ‘react-native’<br>const Element = ({children, value, setValue}) =&gt;{<br>const handleOperation = () =&gt; setValue(value * 2)<br>return (<br>&lt;View&gt;<br>&lt;Text&gt;{value}&lt;/Text&gt;<br>&lt;TouchableOpacity onPress={handleOperation}&gt;<br>{children}<br>&lt;/TouchableOpacity&gt;<br>&lt;/View&gt;<br>)<br>}<br>export default memo(Element)</em></pre><p>This would fix the re-rendering issue. However, it should be used only when the re-rendering is causing some performance issues.</p><h3><strong>9. The useMemo Hook:</strong></h3><p>useMemo returns a memoized value of a function. However, it should be used only when performing expensive computations.</p><p>For instance, suppose we want to filter some data coming from our API by their rating. We could memoize the computation to recalculate the results only when the values change.</p><pre><em>const data = [<br>{id: 1, state: ‘Ajay’, age: 4.5},<br>{id: 2, state: ‘Bijay’, age: 3},<br>{id: 3, state: ‘Chetan’, age: 4},<br>{id: 4, state: ‘David’, age: 5},<br>{id: 5, state: ‘Elen’, age: 4.5},<br>{id: 6, state: ‘Girish’, age: 3},<br>{id: 7, state: ‘Harish’, age: 2},<br>…<br>{id: 1000, state: ‘Ishita’, age: 4.5},<br>]</em></pre><p>If we wish to filter the data based on the rating (without memoization), we may use up a lot of memory. For such, we don’t want to unnecessarily recalculate the values when other components re-render. We want to re-render or re-calculate only when the dependent rating changes.</p><p>Let’s see how we can achieve this with useMemo.</p><pre><em>import React, {useMemo} from ‘react’<br>import {FlatList} from ‘react-native’<br>import data from ‘./data’<br>const App = () =&gt;{<br>const rateCompare = 3;<br>const computedValue = useMemo(() =&gt; {<br>//supposed computationally intensive calculation<br>const result = data.filter((d) =&gt; d.rating &gt; rateCompare);<br>return result;<br>}, [rateCompare]);</em></pre><pre><em>const renderItem = ({ item }) =&gt; (<br>&lt;View&gt;<br>&lt;Text&gt;{item.state}&lt;/Text&gt;<br>&lt;/View&gt;<br>);<br>return (<br>&lt;FlatList<br>data={computedValue}<br>renderItem={renderItem}<br>keyExtractor={item =&gt; item.id}<br>/&gt;<br>)<br>}</em></pre><p>We assumed that we have huge data coming from our API and needed to perform a computationally intensive calculation. Although we’ve used a simple filter operation, we could be doing series of calculations here. This is a good use case for the useMemo hook.</p><p>By using useMemo, we can cache (memoize) the results for the value specified in the dependency array. For instance, if the rateCompare constant was 3 the first time it is run, the function will not recalculate anytime the value of rateCompare is 3 even if the entire components re-render. It will only recalculate when the value changes.</p><h3><strong>10. The useCallback Hook:</strong></h3><p>The useCallback hook is similar to useMemo but it returns a memoized callback.</p><pre><em>import React, {useState, useEffect, useCallback} from ‘react’<br>import {FlatList} from ‘react-native’<br>import data from ‘./data’<br>const App = () =&gt;{<br>const [values, setValues] = useState([]);<br>const rateCompare = 3;<br>const valuesCallback = useCallback(() =&gt; {<br>//supposed computationally intensive calculation<br>const result = data.filter((d) =&gt; d.rating &gt; rateCompare);<br>setValues(result);<br>}, [rateCompare, setValues]);<br>useEffect(() =&gt; {<br>valuesCallback();<br>}, [valuesCallback]);<br>const renderItem = ({ item }) =&gt; (<br>&lt;View&gt;<br>&lt;Text&gt;{item.state}&lt;/Text&gt;<br>&lt;/View&gt;<br>);</em></pre><pre><em>return (<br>&lt;FlatList<br>data={values}<br>renderItem={renderItem}<br>keyExtractor={item =&gt; item.id}<br>/&gt;<br>)<br>}</em></pre><p>This does the same thing as the useMemo example. However, because useCallback returns a function, we need to call that function to get the value. Here, we have called the function in a useEffect hook and then rendered the values in a FlatList component.</p><p>We could equally have called the function in a Button or TouchableOpacity component. That way the computation will run whenever the button is pressed.</p><pre><em>Button onPress={valuesCallback} title=”Example button” /&gt;</em></pre><p>While React.memo can optimize an entire component, useMemo and useCallback can optimize a calculation or process. However, each of these should be used only when they are necessary, otherwise, they could even compound the performance issue.</p><p>It is recommended to first write the calculation or component without memoization and only optimize (memoize) it if it is causing performance issues.</p><h3><strong>11. Optimize Android App Size:</strong></h3><p>To optimize the application size of a react native application you should</p><p>- <em>Use Proguard to minimize the application size.<br>- Don’t store raw JSON data. Compress it or convert it into static object IDs<br>- Optimize native libraries.<br>- Compress images and other graphic elements. Another alternative to reduce image size is using file types like APNG in place of PNG files.<br>- Optimize the distribution process by taking advantage of Android App Bundles when releasing a production version of your app.</em></p><h3><strong>12. Use Firebase Performance Monitoring:</strong></h3><p>Firebase Performance Monitoring is a service provided by Google that helps you to gain insights into the performance characteristics of your app. You should use the @react-native-firebase/perf for React Native to collect performance statistics and data from your apps, then review and analyze that data in the Firebase console.</p><h3><strong>13. Remove junk</strong>:</h3><p>This is also the right time to clean your app code. Try to remove unused codes, folders, files, and dependencies from package.json. Also, to reduce your assets, there is a great tool that does lossless compression.</p><h3><strong>14. Run Native Driver for Animation:</strong></h3><p>Most programmers prefer to run animations in a JavaScript thread that further descends down their loading speed on the app. JS thread gets blocked when used for rendering animations &amp; hence, doing so is not advisable as a part of react native app development strategy.<br>It’s possible to give a native modification to animations before you start running animations with the support of animation APIs that can be serialized. So, all you need to do is to use native codes to run the animations on the UI thread so that you don’t have to worry about animations even if Javascript threads get blocked resulting in react native android slow performance.<br>Here are some native driver configurations for animation APIs:</p><pre><em>import React, {useRef} from ‘react’<br>import {Animated} from ‘react-native’<br>const App = () =&gt;{<br>const opacity = useRef(new Animated.value(0)).current<br>const showVal = () =&gt;{<br>Animated.timing(opacity, {<br>toValue: 1,<br>duration: 500,<br>useNativeDriver: true,<br>}).start();<br>}<br>…<br>return (<br>&lt;View&gt;<br>&lt;Animated.View&gt;<br>&lt;Animated.Text&gt;Text to show&lt;/Animated.Text&gt;<br>&lt;/Animated.View&gt;<br>&lt;Button title=”Show” onPress={showVal} /&gt;<br>&lt;/View&gt;<br>)<br>}</em></pre><p>These are the solutions over a several memory leakages in react-native app that slows down the app’s performance. Hope the above tricks will help you to optimise the performance of your app.</p><p>Thank you!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a72ae69c5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social login for React-Native app 
 (Facebook, LinkedIn, Gmail)]]></title>
            <link>https://medium.com/@milind.patil/social-login-for-react-native-app-facebook-linkedin-gmail-815c4832f77?source=rss-76aeacd37e36------2</link>
            <guid isPermaLink="false">https://medium.com/p/815c4832f77</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[social-login]]></category>
            <category><![CDATA[social-media-login]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Milind Patil]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 12:30:02 GMT</pubDate>
            <atom:updated>2022-04-12T06:02:26.489Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Social login for React-Native app </strong><br> (Facebook, LinkedIn, Gmail)</h3><p>Hello guys, nowadays almost every mobile app has Login with social media. This is most common and widely used feature. Here we will see how to integrate most commonly used Login with Google, Facebook, and LinkedIn into your React Native Android and iOS app. <br>With the use of login with social media we don’t need to manage few steps to enter into the app like SignIn, Registration, Verify OTP, etc</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3xz2BLHPfdkbJXniM0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Falcrego-loop-eternal-3xz2BLHPfdkbJXniM0&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F3xz2BLHPfdkbJXniM0%2Fgiphy.gif%3Fcid%3D790b76115ede4243c08c4ed63ca8ce42ad0da40748ef3e3a%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b0927d497b2e06e43a011810a8470a/href">https://medium.com/media/b5b0927d497b2e06e43a011810a8470a/href</a></iframe><p>So, let’s start with integration of Login with social media in detail and step by step.</p><h3><strong>1. Login With Google</strong></h3><ul><li>Create react native project<br><em>$ react-native init sociallogin</em></li><li>Install Dependency <br>To use Google SignIn, Google SignIn Button and status Codes we need to install react-native-google-signIn dependency <br><em>$npm install react-native-google-signin — save</em></li><li>Install Cocoa Pods <br><em>$cd ios &amp;&amp; pod install &amp;&amp; cd ..</em></li></ul><p><strong>Step 1: Create Firebase Project</strong></p><p><strong>A. </strong>Create Firebase Project<strong> </strong>on <a href="https://console.firebase.google.com/"><em>https://console.firebase.google.com/</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*qkcEL0zsmsDkkRooiqgPpA.png" /></figure><p><strong>B. </strong>Select android platform</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aMTSmaPXCyzx33FGT3xa3w.png" /></figure><p><strong>C. </strong>Enter the name of your package and SHA1 key→Register App <br> following image shows a step to find a SHA1 key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*PZJKdjF2hE5IWeV553pv5g.png" /></figure><p><strong>D. </strong>Download config file → move it to Android app module directory → go to Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*GQ2L2dZmzWs_-Wg7kJGrtg.png" /></figure><p>then Add firebase SDK and continue to console.</p><p><strong>Step 2:</strong> <strong>Enable Google Login in Firebase</strong></p><p>Authentication → Sign-In Method → Google</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*-kL-mQ_nz7pyrGxEtW2Yqw.png" /></figure><p>We need to give a name for your Auth consent screen<strong> </strong>and save your web client Id. This will be used to integrate the React Native app with Firebase.</p><p><strong>Step 3: Implement Google auth functions in RN app</strong> <br>This includes</p><h4>A. Google Login button</h4><pre>import { GoogleSignin, GoogleSigninButton, statusCodes } from ‘react-native-google-signin’;</pre><pre>// Component inside render function<br>&lt;GoogleSigninButton<br> style={{ width: 192, height: 48 }}<br> size={GoogleSigninButton.Size.Wide}<br> color={GoogleSigninButton.Color.Dark}<br> onPress={this._signIn}<br> disabled={this.state.isSigninInProgress} /&gt;</pre><h4>B. Configure Sign In</h4><pre>GoogleSignin.<strong>configure</strong>({<br> webClientId:<br>‘XXXXXXX6frb3cb39agad7h6sq14sbdb5guigg1.apps.googleusercontent.com’,<br> offlineAccess: true,<br> hostedDomain: ‘’,<br> forceConsentPrompt: true,<br>});</pre><h4>C. Sign In &amp; Sign Out function</h4><pre>const <strong>signInViaGoogle </strong>= async () =&gt; { <br> try {<br>    await GoogleSignin.hasPlayServices({<br>     // Check if device has Google Play Services installed<br>     // Always resolves to true on iOS<br>     showPlayServicesUpdateDialog: true,<br>    });<br>    const userinfo = await GoogleSignin.signIn();<br>    setUserInfo(userinfo);<br>  } <br>  catch (error) {<br>   if (error.code === statusCodes.SIGN_IN_CANCELLED) {<br>   Alert.alert(‘User Cancelled the Login Flow’);<br>  } <br>   else if (error.code === statusCodes.IN_PROGRESS) {<br>   Alert.alert(‘Signing In’);<br>  } <br>  else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {<br>   Alert.alert(‘Play Services Not Available or Outdated’);<br>  } <br>  else {<br>   Alert.alert(error.message);<br>  }<br> }<br>}; <br> <br>const <strong>logoutFromGoogle </strong>= async () =&gt; {<br>try {<br>  await GoogleSignin.revokeAccess();<br>  await GoogleSignin.signOut();<br>  // Removing user Info<br>  setUserInfo(null);<br> } <br>catch (error) {<br>  console.error(error);<br>}<br>};</pre><p>Now you are able to login via Google.</p><p>Following screenshots shows the stepwise flow of Login via Google:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*NsO1MD0KLO-GAsriJOz-2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*hZUIW6OLiiKgHagqqKh9sQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*0OKp_7fS-YjFjNbVU3Ma5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*ujSV0zLReoufuiaBvI0THw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*XLxHziKKAKbECDh7tWVL7A.png" /></figure><h3><strong>2. Login With Facebook</strong></h3><ul><li>Installation of dependency <br><em> $ npm install react-native-fbsdk –save</em></li><li>Install the cocoa pods<br><em>$ cd ios &amp;&amp; pod install &amp;&amp; cd ..</em></li></ul><p><strong>Step 1: Create a new App on Facebook console</strong></p><p>First of all,<strong> </strong>we need to register our app’s package/bundle name on Facebook Console viz. <a href="https://developers.facebook.com/">https://developers.facebook.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*Xd89qtq0a2jxpK-1ZYNAPg.png" /></figure><p>Select FacebookLogin → setUp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*-hUz5cTtE37pI6u6WazKDw.png" /></figure><p>Update the basic details and adding a specific platforms<br> -Add Android Platform</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*MRlFJMpYt6m1sN39MuwWRQ.png" /></figure><p>-Add Facebook App Id in Android code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*-zkqVLqlzA0oYn3NNzV57Q.png" /></figure><p><strong>2. Enter the Details and Add Platforms (Add Android Platform)</strong></p><p>Enter some details inside Basic submenu of Dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*tTJlEqyVgH2v7MWCrWAKmg.png" /></figure><p>We need a keyHash using SHA1:<br>For finding the SHA1 fingerprint you can click on below url and can generate a Release Key Hash or Debug Key Hash using Release SHA1 or Debug SHA1 respectively:</p><p>For getting a Key Hashes, visit<br><a href="http://tomeko.net/online_tools/hex_to_base64.php"><em>http://tomeko.net/online_tools/hex_to_base64.php</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*jNAaD-Nz4bxyoBNOWeT12g.png" /></figure><p>After saving the above changes, we must add an app id in AndroidManifest file.</p><p><strong>Step 3: Add Facebook App Id in AndroidManifest</strong></p><pre>Add meta-data in the AndroidManifest.xml file<br><em>&lt;meta-data android:name=”com.facebook.sdk.ApplicationId” </em><br><em> android:value=”@string/facebook_app_id”/&gt;</em></pre><ul><li>Add the App ID in the string.xml file:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*XZ20E7jOq5jB4AVXI7qc5w.png" /></figure><ul><li>copy this AppId and paste it in string.xml</li></ul><pre><em>&lt;string name=”facebook_app_id”&gt;1155593782872016&lt;/string&gt;</em></pre><p><strong>Step 4: Add iOS Platform</strong></p><p>By copying the BundleId of our project from Xcode, we need to paste it in the field shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*Dl0D9gE6c-aZe1Mep-a4vg.png" /></figure><p><strong>Step 5: Some platform specific changes in iOS code</strong></p><p>For iOS plattform, we have to open iOS project in XCode and follow these steps:</p><ul><li>Right-click on the info.plist file→ Open As → select Source Code</li></ul><p>We can see info.plist file in the XML format. We have to replace the Facebook App Id here at two places.</p><ul><li>Open AppDelegate.m and add the following lines:</li></ul><pre>#import &lt;FBSDKCoreKit/FBSDKCoreKit.h&gt;</pre><pre>[[FBSDKApplicationDelegate sharedInstance] application:application<br>didFinishLaunchingWithOptions:launchOptions]; <br> <br>- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary&lt;UIApplicationOpenURLOptionsKey,id&gt; *)options {<br>BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]<br>];<br>// Add any custom logic here.<br>return handled;<br>}</pre><p>Finally, you are ready to login via Facebook! <br>Following are the screenshots which can help you too understand a stepwise flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*oJcChofH_xivfcML6KvGWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*JlLF3EED4eSKFpErwwVcWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*BaHz7pwcn_Th-y_4avfUKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*cvMjeClo3Bbex5jMgq-u1A.png" /></figure><h3>3. Login With LinkedIn</h3><p><strong>Step 1: Create app on LinkedIn console</strong></p><p>go to <a href="https://developer.linkedin.com/"><em>https://developer.linkedin.com/</em></a><em> </em><br>and create an app and by filling some details given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*6mbdPfdb9LED7B8JvAufbQ.png" /></figure><p>Enter the App name, url of your linkedIn page, privacy policy url, App logo. <br>You will see a following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*hxkosLofMBmgXtooSlFu1Q.png" /></figure><p>Copy this ClientID. <br>It’s showing <br>“This app is not verified as being associated with this company” <br>You need to verify this LinkedIn Page by following 1–3 steps:</p><p><strong>Step 2: Verify the App</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*q5emssrPOPjeqjdV9TkRWA.png" /></figure><p>Copy the Generate URL → Copy URL → Hit on browser <br>It sends a verification code on your LinkedIn account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*adaLA-aWrpO89aDvKK8Ehg.png" /></figure><p>Go to your LinkedIn account, click on Verify</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*-S2cUlNrKDcAWMKEQNKJVw.png" /></figure><p>After refreshing a page of linkedIn console, you will see it as a verified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*XUlwdAvGfi958SY6-ATT-Q.png" /></figure><p>Select 2nd tab ’Auth’ and copy a Client ID and Client Secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*mTqiRl1pgVsdJ6_IgL9exA.png" /></figure><p><strong>Step 3: Enable the LinkedIn Login option from Products list:<br></strong>Now go to 3rd tab ‘Product’ and select an option Sign in with LinkedIn</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*kaRzrGLEakbjNoKtNpTMAA.png" /></figure><p><strong>Step 4: Install the dependencies &amp; Cocoa Pods:</strong></p><p><em>$ npm install react-native-linkedin — save<br>$ npm install react-native-webview –save<br>$ cd ios &amp;&amp; pod install &amp;&amp; cd ..</em></p><p><strong>Step 5: Add following code:</strong></p><pre>Import a LinkedInModal from npm install react-native-linkedIn<br>import LinkedInModal from ‘react-native-linkedin’;<br>const LoginWithLinkedIn = props =&gt; {<br>const [email, setEmail] = useState();<br>const [payload, setPayload] = useState();<br>var modal;</pre><p>Use LinkedInModal, onSuccess props of LinkedInModal gives a token, which is used to fetch the API for getting the userDetails:</p><pre>return (<br> &lt;View style={styles.container}&gt;<br>  &lt;LinkedInModal<br>   ref={ref =&gt; {<br>   modal = ref;<br>   }}<br>   renderButton={_handleLinkedInLogin}<br>   style={{border: ‘1 solid’, fontSize: 20}}<br>   clientID=” ______________”<br>   clientSecret=” ___________ ”<br>   redirectUri=”____________”<br>   onSuccess={token =&gt; {<br>    getUser(token);<br>    getUserEmailId(token);<br>   }}<br>   onError={() =&gt; {<br>    console.log(‘Error’);<br>   }}<br>  /&gt;<br> &lt;/View&gt;<br>);</pre><p>You have to mention the clientId and clientSecret that were copied during the step 2.</p><p>GetUser() function gives an object that contains some user details such as id, firstName, lastName, profilePicture.</p><pre>const getUser = async data =&gt; {<br> const {access_token, authentication_code} = data;<br> if (!authentication_code) {<br>  const response = await fetch(<br> ‘https://api.linkedin.com/v2/me?projection= (id,firstName,lastName,profilePicture(displayImage~:playableStreams) )&#39;,<br>{<br> method: ‘GET’,<br> headers: {<br>  Authorization: ‘Bearer ‘ + access_token,<br> },<br> },<br>);<br>const apipayload = await response.json();<br>setPayload(apipayload);<br>}<br>else {<br> alert(`authentication_code = ${authentication_code}`);<br>}<br>};</pre><p>For finding an emailId of user we have to call the following API</p><pre>const getUserEmailId = async data =&gt; {<br> const {access_token, authentication_code} = data;<br> if (!authentication_code) {<br>  const response = await fetch(<br>  ‘https://api.linkedin.com/v2/clientAwareMemberHandles?  q=members&amp;projection=(elements*(primary,type,handle~))&#39;,<br>  {<br>  method: ‘GET’,<br>  headers: {<br>   Authorization: ‘Bearer ‘ + access_token,<br>  },<br>  },<br>  );<br>  const emailpayload = await response.json();<br><br>  setEmail(emailpayload.elements[0][‘handle~’].emailAddress);<br>  handleGetUser();<br>  }<br>  else {<br>   Alert.alert(`authentication_code = ${authentication_code}`);<br>  }<br>};</pre><p>After getting the user information, we are navigating user to the HomeScreen</p><pre>const handleGetUser = useCallback(() =&gt; {<br>if (payload) {<br> if (props.setFirstName) {<br> props.setFirstName(payload.firstName.localized.en_US);<br>}<br> if (props.setLastName) {<br>  props.setLastName(payload.lastName.localized.en_US);<br> }<br> if (props.setProfileImage) { <br> if (payload.profilePictfsure !== undefined&amp;&amp;<br>payload.profilePicture[‘displayImage~’] !== null&amp;&amp;<br>payload.profilePicture[‘displayImage~’].elements[3].identifiers[0].identifier !== null &amp;&amp;<br>payload.profilePicture[‘displayImage~’].elements[3].identifiers[0].identifier !== undefined)<br> {<br> props.setProfileImage(payload.profilePicture[‘displayImage~’].elements[3].identifiers[0].identifier,);<br>}<br>else {<br> props.setProfileImage(<br> ‘<a href="https://picsum.photos/200">https://picsum.photos/200</a>&#39;,);<br> }<br>}<br>if (props.setLinkedInId) {<br> props.setLinkedInId(payload.id);<br>}<br>if (email) {<br> if (props.setEmailId) {<br> props.setEmailId(email);<br> props.setIsLoggedIn(true);<br> props.navigation.replace(‘HomeScreen’, {<br>  FName: payload.firstName.localized.en_US,<br>  LName: payload.lastName.localized.en_US,<br>  EmailId: email,<br>ImageUri:payload.profilePicture[‘displayImage~’].elements[3].identifiers[0].identifier,<br> From: ‘LINKEDIN’,<br> });<br>}<br>}<br>}<br>}, [email, payload, props]);</pre><p>Here you can display the retrieved ProfilePicture along with the first name, last name, emailId on your HomeScreen.</p><pre>import {AsyncStorage} from ‘react-native-community/async-storage’;<br>import {WebView} from ‘react-native-webview’;</pre><pre>const HomeScreen = (props, route, navigation) =&gt; {</pre><pre>const [isLoggedOut, setIsLoggedOut] = useState(false);<br>const {FName, LName, EmailId, ImageUri, From} = props.route.params;<br>const [userInfo, setUserInfo] = useState(null);<br>const [gettingLoginStatus, setGettingLoginStatus] = useState(true);<br>const [fName, setfName] = useState(FName.replace(/[‘“]+/g, ‘’));<br>const [lName, setlName] = useState(LName.replace(/[‘“]+/g, ‘’));<br>const [email, setlEmail] = useState(EmailId.replace(/[‘“]+/g, ‘’));<br>const [from, setlFrom] = useState(From.replace(/[‘“]+/g, ‘’));<br>const [imageUrl, setImageUrl] = useState(props.route.params.ImageUri.replace(/[‘“]+/g, ‘’),);</pre><pre>const logoutFun = async () =&gt; {<br> setIsLoggedOut(true);<br> await AsyncStorage.setItem(‘ISLOGGEDIN’, ‘false’);<br> props.navigation.replace(‘LoginWithLinkedIn’);<br>};</pre><pre>return (<br>&lt;View style={styles.container}&gt;<br>&lt;Image<br>style={styles.images}<br>source={{uri: imageUrl}} <br>/&gt;<br>&lt;Text style={styles.text}&gt;{fName + ‘ ‘ + lName}&lt;/Text&gt;<br>&lt;Text style={styles.text}&gt;{email}&lt;/Text&gt;<br>&lt;View style={{marginTop: 200}}&gt;<br>{isLoggedOut === true &amp;&amp; (<br>&lt;View style={{width: 1, height: 1}}&gt;</pre><pre>&lt;WebView<br> source={{uri: ‘https://www.linkedin.com/m/logout&#39;}}<br> javaScriptEnabled<br> domStorageEnabled<br> sharedCookiesEnabled<br>/&gt;<br>&lt;/View&gt;<br>)}<br>&lt;/View&gt;<br>&lt;/View&gt;<br>);<br>};</pre><pre>const mapStateToProps = state =&gt; ({<br>linkedInInfo: state.LoginWithLinkedInReducer,<br>});<br>export default connect(mapStateToProps, {})(HomeScreen);</pre><p>In this way we can Login via LinkedIn, <br>which is shown in the following screenshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*u3H4dXao9tIn9-YtLIqq5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*TP7tXWH_oHf-0-R12u_qIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*QVQVXqJ89waRPEjbxhcpvw.png" /></figure><p>By integrating all the above 3-ways for login, we can give a provision to login via Google, Facebook and LinkedIn on a single screen. So that user can select any of the three.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815c4832f77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>