React Native – How To Make Conditional Rendering Safer In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Make Conditional Rendering Safer In React Native ?).

In this article, We will learn how to use conditional rendering safer in react native. Sometimes, depending on the conditions, we need to perform various actions or present the particular view. To do this, we will use the conditional statements.

Very soon after start of creating first app every developer needs to render component in one way or another depending on props. When one start searching, the first answer is inside React documentation. The answer is “Conditional Rendering”. But after a while many of us starts facing errors in React Native (or wrong rendering in React for web) that seems to jump on occasionally to reappear some time later. This article will explain what is happening and how to prevent further mistakes.

A famous quote about learning is :

” That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way.”

So Let’s begin.


Conditional Rendering

Conditional rendering using inline If with logical && (AND) operator as React docs says:

You may embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element — React docs: Conditional Rendering


Example 1Text Example

{someValue && (
  <View style={styles.field}>
    <Text>{someValue}</Text>
  </View>
)}

This handy solution is used by many and it’s nothing new for our community to see in the code. How and why it can crash your React Native app?

When using it widely in our App without proper attention sooner or later we will see this error (or worse scenario our users will see that the app crashed):

Invariant Violation: Text strings must be rendered within a <Text> component.

Then we see such an error in our logs and scratch our head because usually it works, it may crash for one particular data entry or after some small API change. What happened? Hint: someValue type matters.


Example 2 – Array Example

Another common example of javascript operator wrong usage is rendering something is array contains any elements:

// Sooner or later this code will surprise users.
// Just wait for an empty array.
{dataEntries.length && (
  <View>
    <Text>Visible only when array is not empty</Text>
  </View>
)}

Above example looks fine at a first glance. Array’s length will be 0 which is falsy thus condition is not satisfied and following component is not rendered — simple. This reasoning is partially good but author might forgot about one little fact that will surprise users at some point. Let’s take a closer look.


How logical AND && operator in JavaScript works?

Let’s see the docs again:

OperatorSyntaxDescription
Logical AND (&&)expr1 && expr2If expr1 can be converted to true, returns expr2; else, returns expr1.

If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

Examples of expressions that can be converted to false are:

  • null;
  • NaN;
  • 0;
  • empty string ("" or '' or ``);
  • undefined.


String Variable

Boolean('hello world')
// -> true

Boolean('')
// -> false

Boolean(' ')	// space
// -> true

'' && 'conditionally returned string'
// -> ''

'hello world' && 'conditionally returned string'
// -> 'conditionally returned string'

Empty string is falsy so AND operator will return '' because the condition is not fulfilled. Returning '' directly into ReactNative JSX will produce error Text strings must be rendered within a <Text> component and cause crash.


Numeric Variable

Boolean(-1)
// -> true

Boolean(0)
// -> false

Boolean(1)
// -> true

0 && 'conditionally returned string'
// -> 0

1 && 'conditionally returned string'
// -> 'conditionally returned string'

Zero is falsy so logical AND operator will return 0 as the condition is not met. Returning 0 into ReactNative JSX will cause crash with Invariant Violation error again.


Other Variable Types

Boolean(null)
// -> false

Boolean(undefined)
// -> false

Boolean({})
// -> true

Boolean([])		// worth noting!
// -> true

From the above examples the most interesting from React Native developer’s point of view is array. Usually when we put array into conditional render we would like not to render anything if array is empty. Passing an empty array into logical expression without any preparation will mislead us. What one would need to do is to check whether length exists and is equal to 0.


Why React Native crashes?

Rendering string in React Native must be wrapped with <Text>...</Text> component. But when we want to hide entire component when variable is empty with conditional rendering it may return an empty string directly into JSX. For example:

let optionalStr = ''

// [...] some logic that leaves `optionalStr` empty

{optionalStr && <Text>{optionalStr}</Text>} // crash

Now we know that above condition is not fulfilled therefore logical AND operator will return optionalStr directly into main JSX.


What about a numeric variable?

Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things. […] — React docs: JSX in Depth

React tries to convert results of our expressions into a string, React element or array. This is why we see Invariant Violation: Text strings must be rendered within a <Text> component even if our variable was Number. It may be misleading while searching for this bug in a production code.


Why Is It Hard To Find React Native Conditional Render Error?

This error is sneaky because it may take a long time before it shows up. Our code may be working like a charm without any issues for months and suddenly something changes on API and type of that nullable variable changes suddenly to empty string or 0.

Why it works with variables that are null or undefined then? It will also work for booleans. React creators make our life easier and by default such variables are ignored in a JSX tree. It is special case and it will not be rendered.

React will also not crash when we put empty array directly into JSX as arrays can render multiple elements.

// below expressions will not crash your React Native app
<View>
  {false}
  {true}
  {null}
  {undefined}
  {[]}
</View>


Different Options To Make Conditional Rendering Safer

We just make sure to convert every variable into Boolean before using logical AND && operator.

We can do it multiple ways:

  • Double negation — !!dangerousData
  • Classic conversion — Boolean(dangerousData)
  • Rethink components architecture


1. Double negation — !!dangerousData

It’s an easy quick fix that will work and some experiments says that it’s execution time is faster than Boolean(dangerousData). We do not recommend it though.

This solution’s main pitfall is a human factor. Someone in our team could think that it is pointless to do double negation as it goes from true -> false -> true. It may lead to “refactor” that will create potential crashes in the future as this error may not reveal itself at first. My number one principle while coding is readability.


2. Classic conversion — Boolean(dangerousData)

This seems readable but as we mentioned above some say that it is slower in execution time so make our own research and decide if it is OK for our particular case. We can find news that in modern browsers it is optimized. We may also use some transpilers to change it before it goes to final code.


3. Rethink components architecture

Maybe we don’t need as many conditional renders in the component. Every component should be small and have simplified logic as much as it can. We have seen many overly complicated components with nested conditional renders and believe me it’s not something easy to maintain as our code grows.


3.1. Use Element Variable

In simple components sometimes we can use trick from React documentation with if and variable assignment preceding return.

// ...
  let message = <Text>'Hello there!'</Text>
  if (isVillain) {
    message = <Text style={styles.deepVoice}>'General React'oni!'</Text>
  }

  return <View>{message}</View>


3.2. Component Is A Function (IF ELSE In Render)

In class components it would be — render method is a function.

In function, we can call return inside if statement and it will not execute further on. It will have the same result as with Element variable above. We don’t need else here because when condition is satisfied execution will go on, otherwise it will be stopped on first render.

import React from 'react'
import { View, Text } from 'react-native'

const Card = ({ loading, error, title }) => {
  let content

  if (error) {
    content = <Text style={{ fontSize: 24, color: 'red' }}>Error</Text>
  } else if (loading) {
    content = <Text style={{ fontSize: 24, color: 'gray' }}>Loading...</Text>
  } else {
    content = (
      <View>
        <Text style={{ fontSize: 60 }}>{title}</Text>
      </View>
    )
  }

  return <View style={{ padding: 24 }}>{content}</View>
}

export default function App() {
  return (
    <View>
      <Card error={true} />
      <Card loading={true} />
      <Card loading={false} title="Title" />
    </View>
  )
}


3.3 Conditional (Ternary) Operator

Another common case: rendering a different React element for when a prop exists and when it doesn’t. We can accomplish this with the ternary operator. Note that a buttonTitle equal to the empty string, "", won’t render, since the empty string is a falsy value. If we did want it to, we could use buttonTitle === undefined to check for that case.

import React from 'react'
import { View, Text, Button } from 'react-native'

const Card = ({ title, buttonTitle }) => (
  <View>
    <Text style={{ fontSize: 60 }}>{title}</Text>
    {buttonTitle ? <Button title={buttonTitle} /> : null}
  </View>
)

export default function App() {
  return (
    <View>
      <Card title="Title" />
      <Card title="Title with button" buttonTitle="Press me!" />
    </View>
  )
}


Explaining The Array Example Solutions

In Previous example, we show that

dataEntries.length && (
  <View>
    <Text>Visible only when array is not empty</Text>
  </View>
)}

Now we understand that what really happens in above code is returning length to directly into JSX. It happens when length is falsy and it comes from logical operator implementation.

To simplify the example and make things more visible let’s assume that dataEntries.length is 0 and following View with Text component is <Component />. Now we have:

{0 && <Component />}

This expression returns 0 which is converted to string '0' and we can see it as an error in React Native or as an extra character on the web.

The quickest fix possible is to make sure that we don’t depend on falsy value but on boolean false.

Here are multiple fix scenarios:


Double Negation

{!!dataEntries.length && <Component />}


Classic Conversion

{Boolean(dataEntries.length) && <Component />}


Inline Condition

{(dataEntries.length > 0) && <Component />}


Ternary Operator

{dataEntries.length ? <Component /> : null}


Refactor, Rethink, Make It Safe

let coditionalComponent = null

if(dataEntries.length > 0){
	coditionalComponent = <Component />
}

That’s all about in this article.


Conclusion

In this article, We understood how to make conditional rendering safer in react native. We also explained what is happening and how to prevent further mistakes when we use Conditional Rendering .

Thanks for reading ! I hope you enjoyed and learned about Conditional Rendering concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How To Translate A Design To A Flexible React Native App ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Translate A Design To A Flexible React Native App ?).

In this article, We will learn how to translate a design to a flexible React Native application. React Native is one of many cross-platform frameworks that assist a developer in creating an app that utilises native UI and has a high level of code reuse between platforms. It accomplishes this by acting as a renderer on both iOS and Android for the React framework, which itself has the advantage of allowing web developers to get started in the world of mobile development using familiar concepts. We will discuss the ability to take a static design from a designer and turn it into React native code.

A famous quote about learning is :

” One learns from books and example only that certain things can be done. Actual learning requires that you do those things. “

So Let’s begin.


The Layout System

React Native utilises a very web-like layout system, making heavy use of Flexbox to control the flow and sizing of individual elements on-screen. This gives a head-start to web developers as they already conceptually understand the Flexbox system, however it is totally new to native mobile developers who may be used to visually creating screen layouts in iOS Storyboards or working with XML in Android Layout files. 

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes. We will normally use a combination of flexDirectionalignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.


Design to Code

An important skill to have when developing a cross-platform application is the ability to take a static design from a designer and turn it into code, ensuring that it will adapt correctly to any supported screen size. Typically, this is done by focusing on margins/paddings rather than widths and heights, unless of course a component should have a set width or height, such as a title bar or a button. For example, we envisioned a simple feed item from a social app.

The first step of converting the above design to code is to break it down into its component parts. We infer which elements align with which other elements and which parts should expand to fit either content or container. For example, when we break the design down into Flexbox rows (blue outline) and columns (green outline). Now let’s split these parts out into individual components so that we can define their behaviour more easily, starting with the lowest level components.


1. TitleTextContainer

This is a column view that contains two Text elements. It should match the height of the container it will be put into (in this case, a row with the user image) so we don’t need to add any height values to it. As for the text, it needs to float in the vertical centre of the container and be pinned to the horizontal start. This will be relatively simple:

TitleTextContainer.js

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class TitleTextContainer extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.title}>Jordan Duncan</Text>
                <Text style={styles.subtitle}>2 hours ago</Text>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        justifyContent: 'center',
    },
    title: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#000'
    },
    subtitle: {
        fontSize: 14,
        fontWeight: 'normal',
        color: '#333'
    }
});


2. ActionContainer

This is a fixed-height row view that contains two Text elements. Each element should take up half of the width of the parent, so we will use flex: 1. Again, this is a simple component:

ActionContainer.js

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class ActionContainer extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.textContainer}>
                    <Text style={styles.text}>Like</Text>
                </View>
                <View style={styles.textContainer}>
                    <Text style={styles.text}>Comment</Text>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        backgroundColor: '#951754',
        height: 40,
        borderRadius: 5,
    },
    textContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    text: {
        fontSize: 18,
        fontWeight: 'normal',
        color: '#FFF'
    }
});

Now we can move up a level in our design and use these components.


3. FullTitleContainer

As we have already created our TitleTextContainer view, we can ignore its internal layout and when we do that, it becomes clear that all that is necessary is a row view that contains a fixed size Image and the TitleTextContainer that will flex to fit the remainder of the FullTitleContainer:

FullTitleContainer.js

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

import TitleTextContainer from './TitleTextContainer';

export default class FullTitleContainer extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.image} />
                <TitleTextContainer />
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        paddingLeft: 5,
    },
    image: {
        height: 60,
        width: 60,
        borderRadius: 30,
        backgroundColor: '#0099FF',
        marginRight: 10,
    },

});


4. PostContentContainer

Similarly to the FullTitleContainer, now that we have dealt with the ActionContainer, all we are left with is a column view that contains a dynamic height Text component and our ActionContainer. As the container will expand to fit its contents (the contents will not expand to fit the container), we do not need to apply flex values to any content:

PostContentContainer.js

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

import ActionButtonContainer from './ActionButtonContainer';

export default class PostContentContainer extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.text}>I wish there was an easy way to make cross platform layouts :(</Text>
                <ActionButtonContainer />
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        paddingLeft: 70,
        paddingBottom: 10,
        paddingRight: 10,
    },
    text: {
        fontSize: 18,
        fontWeight: 'normal',
        color: '#000',
        marginVertical: 10,
        paddingBottom: 10,
    },

});

One thing to note here is that we have added a paddingLeft of 70 (image width 60 + padding 10) to the container. This is in order to bring it in line with the title text when we add it to the main component.


5. Putting it all together

Now that we have produced all the component parts, it is clear that the full component just consists of a column view that contains the FullTitleContainer and the PostContentContainer.

App.js

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
import FullTitleContainer from './FullTitleContainer';
import PostContentContainer from './PostContentContainer';

export default class App extends Component {

  render() {
    return (
      <View style={styles.container}>
        <Card>
          <FullTitleContainer />
          <PostContentContainer />
        </Card>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#EEE',
    padding: 20,
    margin: 20,
  },
});

As we can see, it only requires an understanding of Flexbox to allow us to create a flexible, cross-platform layout that will look and perform great on a range of different devices.

That’s all about in this article.


Conclusion

In this article, We understood how to translate a design to a flexible React Native application.

Thanks for reading ! I hope you enjoyed and learned about translate a design To a flexible React Native app. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How To Create Custom Buttons In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Create Custom Buttons In React Native ?).

In this article, We will learn about how to create custom buttons in React Native. React Native is an excellent framework for building native mobile applications. It allows us to build apps that will work on both iOS and Android platforms. Core UI components such as <Button /> look different on each platform, and there are limited styling and customization options. For this and many other reasons, it’s critical to know how to create buttons that look consistent regardless of the operating system. In this article, we’ll walk through how to create various types of custom buttons in React Native.

A famous quote about learning is :

” Tell me and I forget, teach me and I may remember, involve me and I learn.”

So Let’s begin.


Create Button Using Stylesheet

A basic button component that should render nicely on any platform. Supports a minimal level of customization.

For Example – App.js

import React from "react";
import { View, Button, StyleSheet } from "react-native";

const App = () => {
  return (
    <View style={styles.screenContainer}>
      <Button title="Press Button" />
    </View>
  );
};

const styles = StyleSheet.create({
  screenContainer: {
    flex: 1,
    justifyContent: "center",
    padding: 16
  }
});

export default App;

In the above code block, a core <Button /> component is declared and wrapped inside a container. StyleSheet, is an API provided by the React Native framework as an abstraction to CSS StyleSheets.


The Custom Button Component

Now that we’ve set up the main screen, it’s time to turn our attention to the custom button component.

const AppButton = props => (
    // ...
)

Name the custom button component AppButton.

Import the <TouchableOpacity /> and <Text /> components from react-native. To create custom buttons, we need to customize the <TouchableOpacity /> component and include the <Text /> component inside of it to display the button text. Next, create the StyleSheet properties to style the button.

<TouchableOpacity />, as the name suggests, is a touchable component, which means it can respond to the user’s touch. When we press the button, the opacity decreases. We can control the opacity by passing an activeOpacity prop to the <TouchableOpacity /> component.

If we want to change the opacity for all the custom buttons in our app, use the defaultProps property. defaultProps is a property in a React component that sets default values for the prop argument.

After we’ve imported TouchableOpacity, The onPress props expect a function or a function reference that will execute when the user presses the button. The full code for this section is as follows.

For Example App.js

import React from "react";
import { View, Button, StyleSheet, TouchableOpacity, Text } from "react-native";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const AppButton = ({ onPress, title }) => (
  <TouchableOpacity onPress={onPress} style={styles.appButtonContainer}>
    <Text style={styles.appButtonText}>{title}</Text>
  </TouchableOpacity>
);

const App = () => {
  return (
    <View style={styles.screenContainer}>
      <AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />
    </View>
  );
};

const styles = StyleSheet.create({
  screenContainer: {
    flex: 1,
    justifyContent: "center",
    padding: 16
  },
  appButtonContainer: {
    elevation: 8,
    backgroundColor: "#009688",
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 12
  },
  appButtonText: {
    fontSize: 18,
    color: "#fff",
    fontWeight: "bold",
    alignSelf: "center",
    textTransform: "uppercase"
  }
});

export default App;

The custom button should look like this:


Adding More Props In Custom Button Component

Since it’s a custom button component, we have the liberty of piling on additional props. For example, we can add a prop to change the button size or change the background color.

const AppButton = ({ onPress, title, size, backgroundColor }) => (
  <TouchableOpacity
    onPress={onPress}
    style={[
      styles.appButtonContainer,
      size === "sm" && {
        paddingHorizontal: 8,
        paddingVertical: 6,
        elevation: 6
      },
      backgroundColor && { backgroundColor }
    ]}
  >
    <Text style={[styles.appButtonText, size === "sm" && { fontSize: 14 }]}>
      {title}
    </Text>
  </TouchableOpacity>
);

// ...
<AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />;

We’ll see the following result on our screen.


Styling the button using Linear gradient background

By default, React Native doesn’t have an API to create a linear gradient background in a container. Luckily, there’s another expo utility library for React Native that we can use to create linear gradient colors.

We need to create project and import the <LinearGradient /> component from the expo-linear-gradient library. we ‘ll need to make some adjustments in the <AppButton /> component. Wrap the <TouchableOpacity /> component around the <LinearGradient /> component and add the style prop to the <LinearGradient /> component. The colors prop in LinearGradient accepts an array, which contains the color values that will be used to create the linear gradient.

The full code for this section is as below:

For Example – App.js

import React from "react";
import { View, StyleSheet, TouchableOpacity, Text } from "react-native";
import { LinearGradient } from "expo-linear-gradient";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const AppButton = ({ onPress, title }) => (
    <TouchableOpacity onPress={onPress}>
        <LinearGradient
            colors={["#004d40", "#009688"]}
            style={styles.appButtonContainer}
        >
            <Text style={styles.appButtonText}>{title}</Text>
        </LinearGradient>
    </TouchableOpacity>
);

const App = () => {
    return (
        <View style={styles.screenContainer}>
            <AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />
        </View>
    );
};

const styles = StyleSheet.create({
    screenContainer: {
        flex: 1,
        justifyContent: "center",
        padding: 16
    },
    appButtonContainer: {
        elevation: 8,
        backgroundColor: "#009688",
        borderRadius: 10,
        paddingVertical: 10,
        paddingHorizontal: 12
    },
    appButtonText: {
        fontSize: 18,
        color: "#fff",
        fontWeight: "bold",
        alignSelf: "center",
        textTransform: "uppercase"
    }
});

export default App;

We’ll see the following result on our screen.


Controlling button styles using state

As in any React application, we can add styles to our component based on the current value of the state. For example, if we want to disable a button for a certain period of time after it’s pressed, the button must have a disabled background color so that the user knows it’s temporarily inactive.

Add a style property inside the StyleSheet object to represent the disabled color. For this example,  we’ll use black.

const styles = StyleSheet.create({
  // ...
  appButtonDisabled: {
    backgroundColor: "#000"
  }
});

Next, refactor the <AppButton /> component and use the useState hook to change the disabled state.

const AppButton = ({ title }) => {
  const [isDisabled, setDisabled] = useState(false);

  const handlePress = () => {
    setDisabled(true);
    setTimeout(() => setDisabled(false), 3000);
  };

  return (
    <TouchableOpacity
      onPress={handlePress}
      style={[
        styles.appButtonContainer,
        isDisabled && styles.appButtonDisabled
      ]}
      disabled={isDisabled}
    >
      <Text style={styles.appButtonText}>{title}</Text>
    </TouchableOpacity>
  );
};

We can pass a disabled prop to the TouchableOpactiy component to disable the onPress behavior. We can pass an array of style objects to the style prop. So when isDisabled is set to true, we can add the appButtonDisabled property to the style prop array using the && operator.


Styling the button using styled-components

styled-component is a CSS-in-JS library that enables us to write each component with its own style and encapsulate the code in a single location.

React Native follows a certain specification for styling these components. For example, all CSS property names must be written in camelCase — background-color should be specified as backgroundColorborder-width as borderWidth, etc.

This can be a little disorienting for a developer who is approaching mobile app development from a web development background. The styled-components library enables us to write native CSS for styling a React Native component. Under the hood, styled-components simply converts the CSS text into a React Native StyleSheet object.

 We need to install styled-components using npm or yarn package manager. Replace the TouchableOpacity and Text components with ButtonContainer and ButtonText, respectively. These new components will be created using the syntax from styled-components.

const AppButton = ({ onPress, title }) => (
  <ButtonContainer onPress={onPress}>
    <ButtonText>{title}</ButtonText>
  </ButtonContainer>
);

styled-components uses tagged template literals to style the components using backticks (`). Each styled component must have a React Native component attached to it.

const ButtonContainer = styled.TouchableOpacity``;

const ButtonText = styled.Text``;

Inside the backticks, add CSS rules.

const ButtonContainer = styled.TouchableOpacity`
  elevation: 8;
  border-radius: 10px;
  padding-vertical: 10px;
  padding-horizontal: 12px;
  background-color: #951754;
`;

const ButtonText = styled.Text`
  font-size: 18;
  color: #fff;
  font-weight: bold;
  align-self: center;
  text-transform: uppercase;
`;

Putting everything together, our code should look like this:

import React, { useState } from "react";
import { View, StyleSheet, TouchableOpacity, Text } from "react-native";
import styled from "styled-components";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const ScreenContainer = styled.View`
    flex: 1;
    justify-content: center;
    padding: 16px;
`;

const ButtonContainer = styled.TouchableOpacity`
  elevation: 8;
  border-radius: 10px;
  padding-vertical: 10px;
  padding-horizontal: 12px;
  background-color: #951754;
`;

const ButtonText = styled.Text`
  font-size: 18px;
  color: #fff;
  font-weight: bold;
  align-self: center;
  text-transform: uppercase;
`;

const AppButton = ({ onPress, title }) => (
  <ButtonContainer onPress={onPress}>
    <ButtonText>{title}</ButtonText>
  </ButtonContainer>
);

const App = () => {
  return (
    <ScreenContainer>
      <AppButton title="Hey there!" size="sm" />
    </ScreenContainer>
  );
};

export default App;

That’s all about in this article.


Conclusion

In this article, We understood that how to create various types of custom buttons in React Native. As a developer, we must build UI components to match whatever reference or design our design team comes up with. We must make the UI components look precisely as they’re outlined in our client’s plan or prototype.

Thanks for reading ! I hope you enjoyed and learned about creating Custom Buttons in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – Understanding Flexbox Layout

Hello Readers, CoolMonkTechie heartily welcomes you in this article (Understanding Flexbox Layout).

In this article, we will learn about Flexbox layout in React Native. We will discuss the different props of Flexbox layout for styling a component in React Native.

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes. We will normally use a combination of flexDirectionalignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

A famous quote about learning is :

” Wisdom is not a product of schooling but of the lifelong attempt to acquire it. “


So Let’s begin.


1. flex

flex will define how our items are going to “fill” over the available space along our main axis. Space will be divided according to each element’s flex property.

In React Native flex does not work the same way that it does in CSS. flex is a number rather than a string, and it works according to the Yoga.

When flex is a positive number, it makes the component flexible, and it will be sized proportional to its flex value. So a component with flex set to 2 will take twice the space as a component with flex set to 1. flex: <positive number> equates to flexGrow: <positive number>, flexShrink: 1, flexBasis: 0.

When flex is 0, the component is sized according to width and height, and it is inflexible.

When flex is -1, the component is normally sized according to width and height. However, if there’s not enough space, the component will shrink to its minWidth and minHeight.

flexGrowflexShrink, and flexBasis work the same as in CSS.

In the following example, the red, yellow, and green views are all children in the container view that has flex: 1 set. The red view uses flex: 1 , the yellow view uses flex: 2, and the green view uses flex: 3 . 1+2+3 = 6, which means that the red view will get 1/6 of the space, the yellow 2/6 of the space, and the green 3/6 of the space.


2. flexDirection

‘column’/’column-reverse’/’row’/’row-reverse’

Defines the direction of the main axis. Opposite to the web, React Native default flexDirection is column which makes sense, most mobile apps much more vertically oriented.


3. justifyContent

‘flex-start’, ’flex-end’, ’center’, ’space-between’, ’space-around’

Determines the distribution of children along the primary axis. justifyContent describes how to align children within the main axis of their container (parent container). The default value is flex-start.


4. alignItems

‘flex-start’, ‘flex-end’, ‘center’, ‘stretch

Align items along the cross axis. So in a default view, it will control the horizontal alignment of items. alignItems describes how to align children along the cross axis of their container (parent container). alignItems is very similar to justifyContent but instead of applying to the main axis, alignItems applies to the cross axis. The default value is stretch.

For instance, if the parent has a flexDirection set to row. Then the opposite axis is the column. The alignItems will then align the children based on the value provided in vertical(column) axis.


5. alignSelf

‘auto’, ‘flex-start’, ‘flex-end’, ‘center’, ‘stretch’

Align an item along the cross axis overwriting his parent alignItem property. alignSelf can apply the property to a single child within a parent element, instead of applying it to all the children.

alignSelf has the same options and effect as alignItems but instead of affecting the children within a container, we can apply this property to a single child to change its alignment within its parent. alignSelf overrides any option set by the parent with alignItems. The default value is auto.


6. flexWrap

‘wrap’, ‘nowrap’, ‘wrap-reverse’

Controls whether flex items are forced on a single line or can be wrapped on multiple lines. The default value is nowrap.


7. alignContent

‘flex-start’, ’center’, ’flex-end’, ’stretch’, ’space-between’, ’space-around’

Defines the distribution of lines along the cross-axis. This only has effect when items are wrapped to multiple lines using flexWrap. The default value is flex-start.


8. position

‘relative’/’absolute’

The position type of an element defines how it is positioned within its parent.

position in React Native is similar to regular CSS, but everything is set to relative by default, so absolute positioning is always relative to the parent.

If we want to position a child using specific numbers of logical pixels relative to its parent, set the child to have absolute position.

If we want to position a child relative to something that is not its parent, don’t use styles for that. Use the component tree.

For example, Think of our container as a line of people. And we are telling each person to stand 5 meters behind the person in front of him (marginTop: 5). If this person is set to relative he will respect the line and will position himself relatively to the person in front of him. If this person is set to absolute he will ignore all of the people in the line and will position himself as if the line was empty, 5 meters from where the line (his parent container) starts.


9. zIndex

zIndex controls which components display on top of others. Normally, we don’t use zIndex. Components render according to their order in the document tree, so later components draw over earlier ones. zIndex may be useful if we have animations or custom modal interfaces where we don’t want this behavior.

It works like the CSS z-index property – components with a larger zIndex will render on top. Think of the z-direction like it’s pointing from the phone into our eyeball.

On iOS, zIndex may require Views to be siblings of each other for it to work as expected.

In the following example the zIndex of the yellow square to 1.


10. Flex Basis, Grow, and Shrink

  • flexGrow  describes how any space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children. flexGrow accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s flexGrow values.
  • flexShrink describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. flexShrink is very similar to flexGrow and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed. flexShrink accepts any floating point value >= 0, with 1 being the default value. A container will shrink its children weighted by the children’s flexShrink values.
  • flexBasis is an axis-independent way of providing the default size of an item along the main axis. Setting the flexBasis of a child is similar to setting the width of that child if its parent is a container with flexDirection: row or setting the height of a child if its parent is a container with flexDirection: column. The flexBasis of an item is the default size of that item, the size of the item before any flexGrow and flexShrink calculations are performed.


11. Width and Height

The width property specifies the width of an element’s content area. Similarly, the height property specifies the height of an element’s content area.

Both width and height can take the following values:

  • auto (default value) React Native calculates the width/height for the element based on its content, whether that is other children, text, or an image.
  • pixels Defines the width/height in absolute pixels. Depending on other styles set on the component, this may or may not be the final dimension of the node.
  • percentage Defines the width or height in percentage of its parent’s width or height, respectively.

That’s all about in this article.


Conclusion

In this article, We understood about Flexbox layout in React Native. We also discussed the different basic props of Flexbox layout for styling a component in React Native. 

Thanks for reading ! I hope you enjoyed and learned about the Flexbox layout concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How To Create Responsive Layouts In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Create Responsive Layouts In React Native ?).

In this article, we will learn how to create Responsive Layouts in React Native. Native application developers put a lot of effort into making engaging and stable apps that are supported on multiple devices. This means that Android developers have to make sure that their apps are supported on hundreds of devices. iOS developers also need to support their apps on a growing number of devices.

React Native enables developers to develop apps that can run both on iOS and Android. The problem is that the number of devices they need to support now is doubled. One particular problem is making the app responsive. There is no such thing as CSS media queries in React Native. React Native developers need to scale all of their layouts to make the app responsive on smartphones, tablets, and other devices.

A famous quote about learning is :

” I am always ready to learn although I do not always like being taught. “


So Let’s begin.


Problems With Responsive Layout in React Native

React Native developers make their apps work on one-dimensional devices as a default. As a result, the app looks distorted on devices with different dimensions because different devices have different pixel ratios. React Native style properties accept either Density-Independent Pixels (DP) or percentage.


Independent Pixels

A density-independent pixel is a unit of length that enables mobile apps to scale across different screen sizes. DPs are not the classic screen pixels. Rather, DPs are mathematically calculated through the following equation: DP=PX/ScaleFactor.

PX is the number of classic screen pixels, and the scaling factor indicates how much the pixels should be enlarged.

React Native developers can scale DP values to screens of different sizes only if they have the same resolution. The problem is that there are hundreds of different devices and most of them have screens with different resolutions.


Percentage

Most web development frameworks use percentage values to design different layouts. However, React Native style properties like border-radius and border-width do not accept percentage value. Properties that do accept percentage include maxWidthminWidthmargin and height.


Useful Tips for Creating Responsive Layouts for React Native Apps

The following tips will help us develop responsive React Native apps on a massive range of devices.


1. Layout With Flexbox

Components can control layout with a flexbox algorithm. It’s created to keep the proportions and consistency of the layout on different screen sizes.

Flexbox works very similar to CSS on the Web with just a few exceptions which are really easy to learn. When flex prop is a positive number, then components become flexible and will adjust to the screen respective to its flex value. That means that flex equates to flexGrow: [number], flexShrink: 1, flexBasis: 0.

When flex: 0 — it’s sized accordingly to the height and width and is inflexible. If flex is a negative number it also uses height and width but if there is not enough space it will shrink to its minHeight and minWidth.

There are few main properties provided by flexbox, so let’s get through them!

Flex – describes how elements divide space between them. As mentioned above it’s limited to single numbers. If all elements have flex: 1 they will have the same width. In other cases they will split the sum of the flex among themselves.

Flex direction – controls the direction or the main axis of the content layout. You can layout the content in a row or in a column. The default direction is a column because of the nature of mobile device screens.

Justify content – describes the position of content along the main axis. You can align the content to the right-left of the center of the main axis. You can also determine the space between content components.

Align items – aligns content on the cross axis, as opposed to justifyContent that aligns on the main axis.

Flex prop do a really good job of keeping proportions between elements. Regardless of screen size. FlexDirection and justifyContent keep layout behaviour consistent.

There are many more flexbox props. We touched just a few to show how they can be helpful.


2. Aspect Ratio

Another cool prop is aspect ratio which helps keep proportions of our elements under control. Aspect ratio describes the relationship between the width and the height of an image. It is usually expressed as two numbers separated by a colon, like 16:9. Aspect ratio is a non-standard property available only in React Native, and not in CSS. The aspect ratio property controls the size of undefined element dimensions.

For example, we can use the aspectRatio property to adjust images to screen size when our images extend beyond the screen dimensions. We do not need to know the actual width and height of the image, just set the aspect ratio to 1:1. Our images will take all available screen width, without extending beyond the dimensions.


3. Screen Dimensions

It is great when our designs are the same for both platforms, and all types of devices (mobile, tablets, ipads). However, sometimes we have to deal with different layouts for specific screen dimensions or device types.

React Native does not provide properties that can identify the device type or screen size when we work with different layouts. The solution is to use the Dimensions API. The syntax for obtaining the dimensions of a screen is:

import { Dimensions } from 'react-native';

const {width, height} = Dimensions.get(‘window');

Since React Native 0.61 we can also use a hook.

const {width, height} = useWindowDimensions();

Once we obtain the width from supported range screen sizes , we can pick breakpoints from which our layout can change. We can provide different styles to component or hide some parts of the screen. This is similar behaviour to media queries used in CSS.

import { Text, View, Dimensions } from 'react-native';
 
class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      width: Dimensions.get('window').width
    };
  }
 
  render() {
    return (
     <View>
       {this.state.width < 320 ? <Text>width of the past</Text> : <Text>how big is big enough?</Text>}
     </View>
    );
  }
}


4. Detect the Platform

Apart from screen size we can also change the layout depending on which platform app is launched. To achieve this , we can use the Platform module.

There are many cases where it can be used:

In component render function:

<View>
    {Platform.OS === 'ios' ? <Text>Hi Apple!</Text> : <Text>Hi Android!</Text>}
 </View>

In styles:

cube: {
    width: Platform.OS === 'ios' ? 200 : 300,
    aspectRatio: 1
  }

The Platform module provides select method which can accept any type of args. With this flexibility, we can achieve the same effect as above but cleaner code:

const Logo = Platform.select({
  ios: () => require('Apple'),
  android: () => require('Android'),
})();
 
<Logo />;

In styles:

import {Platform, StyleSheet} from 'react-native';
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});


5. Device Rotation

Many apps can work in portrait and landscape mode. If this is the case for our app , we have to ensure that the layout doesn’t break when changing orientation. As we can expect sometimes the layout can change drastically when we flip the device. Our components may need different styling depending on the orientation. Unfortunately, by default rotation of the device does not trigger a re-render. That’s why it has to be handled manually. We already have the knowledge required to build our own and it’s quite easy!

class RotateComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
 
  getOrientation = () => {
    if (Dimensions.get('window').width < Dimensions.get('window').height) {
      this.setState({ orientation: 'portrait' });
    } else { this.setState({ orientation: 'landscape' }); }
  };
 
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
  render() {
    return (
      <Text>{this.state.orientation}</Text>
    );
  }
}

If we need to support orientation change across the app, it’s a good idea to use HOC to inject orientation.

const HOC = WrappedComponent => class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
      getOrientation = () => {
        if (Dimensions.get('window').width < Dimensions.get('window').height) {
          this.setState({ orientation: 'portrait' });
        } else { this.setState({ orientation: 'landscape' }); }
      };
 
      render() {
        return <WrappedComponent {...this.props} orientation={this.state.orientation} />;
      }
};

We can also pass getOrientation to onLayout prop exposed by View component. It is fired on every layout change, so it should be used carefully.

If we want to take advantage of the orientation in our styles, remember that it should be inline styles. We already know how to trigger a re-render of the layout when the device is rotated, but the styles are loaded only once. That’s why styles which affect the layout on rotation should be placed inline.

That’s all about in this article.


Conclusion

In this article, We understood how to create Responsive Layouts in React Native. We reviewed responsive layouts challenges in React Native apps and provided solutions for making our responsive layouts much easier. Responsiveness solutions include techniques like Flexbox, dimensions, and aspect ratio properties. In addition, we can detect the device platform and screen orientation to adjust our app to different screen sizes. 

Thanks for reading ! I hope you enjoyed and learned about the Responsive Layout challenges and solutions in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – Understanding Direct Manipulation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Direct Manipulation in React Native. Direct manipulation is an important concept in react native.

To understand the direct manipulation concept, we will discuss the below topics :

  • What is Direct Manipulation ?
  • How Direct Manipulation Works ?
  • UseCase using setState and setNativeProps

A famous quote about learning is :

” We now accept the fact that learning is a lifelong process of keeping abreast of change. And the most pressing task is to teach people how to learn.”

So, Let’s begin.


What is Direct Manipulation ?

The definition of Direct Manipulation says that 

Direct Manipulation is the process of making a component changes directly without using state/props or render whole hierarchies of components for a small change in one component.

Before the understanding of direct manipulation, we need to understand that how any components display on the UI Screen ?

The answer is that we need to write code for that components in render() method to display any component in the screen.

Now, what if you want to add/change any component?

The answer is we have to change state or props, otherwise the render() method will not be called. The render() method renders the whole component hierarchies even if there is a change in the only one component.

So the solution for this problem is Direct Manipulation that does not render all the component hierarchies for one component change.

In other way, we can say that

It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree (or render the whole hierarchies of components for a small change in one component). This process is called Direct Manipulation.


How Direct Manipulation Works ?

In this section, we will see that how to work Direct Manipulation.

Direct Manipulation uses setNativeProps and Refs. setNativeProps is the react native equivalent to setting the properties directly on a DOM node.

and then, next question is “When to use setNativeProps and Refs ?”

Use setNativeProps when frequent re-rendering creates a performance bottleneck.

Direct manipulation will not be a tool that we reach for frequently; we will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within our React components, which makes our code more difficult to reason about. Before we use it, try to solve our problem with setState and shouldComponentUpdate.


UseCase

Let’s understand setNativeProps /Refs and setState concepts with one use case with the below code examples:

We have one TextInput which should be cleared when button is pressed.


1. Using setState

import React from 'react';
import {
  TextInput,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

export default class App extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        inputText: '',
      }
    }
    clearText = () => {
        this.setState({
            inputText : ''
        })
    }

    render(){
        console.log("render method is called")
        return( 
        <View style={{justifyContent :'center',flex:1}}>
            <TextInput
            style={{height: 50,marginHorizontal: 20, borderWidth: 1, borderColor: '#ccf'}}
            value = {this.state.inputText}
            onChangeText= {(text) =>{
                this.setState({
                    inputText : text
                })
            }}
            />
            <TouchableOpacity onPress={()=>this.clearText()}>
                <Text>Clear Text</Text>
            </TouchableOpacity>
        </View>
        );
    }
}

In this above code example, we change the text or clear button each time. Render method is called which re-render the whole component even if there is a change for the component.


2. Using setNativeProps

import React from 'react';
import {
  TextInput,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

export default class App extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        text: '',
      }
    }

    clearText = () => {
      this._textInput.setNativeProps({
        text: ' '
      });
    }

    render(){
        return( 
        <View style={{justifyContent :'center',flex:1}}>
            <TextInput
            ref={component => { this._textInput = component}}
            style={{height: 40,marginHorizontal: 18, borderWidth: 1, borderColor: '#ccc'}}
            onChangeText= {(text) =>{
                this._textInput.setNativeProps({text: text});
            }}
            />

            <TouchableOpacity onPress={clearText}>
                <Text>Clear Text</Text>
            </TouchableOpacity>
        );
    }
}

In above code example, render method will not be called when we click on clear text button or text is changed.

So Here the component will not be re-rendered. We can change any props of a component using setProps and Refs without using re-render().

Some times If we update a property that is also managed by the render function, we might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from setNativeProps will be completely ignored and overridden. So we need to avoid conflict with the render function.

By intelligently applying shouldComponentUpdate, we can avoid the unnecessary overhead involved in reconciling unchanged component subtrees, to the point where it may be performant enough to use setState instead of setNativeProps.

That’s all about in this article.


Conclusion

In this article, We understood about Direct Manipulation in React Native. We also discussed how Direct Manipulation works with use-case. In Summary, we can say that :

  • Direct Manipulation is the process of making a component changes directly without using state/props.
  • Direct Manipulation helps to prevent render all the component hierarchies for one component change.
  • Direct Manipulation uses setNativeProps and Refs when frequent re-rendering creates a performance bottleneck.

Thanks for reading ! I hope you enjoyed and learned about the Direct Manipulation concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How To Secure Mobile Application In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn how to secure Mobile application in React Native. We will discuss Security related areas and techniques to secure mobile application. React Native is a popular cross-platform JavaScript framework. Components of React Native apps are rendered in Native UI. In this article, we will focus on the security side of the framework. In this article, we will focus on the security side of the framework.

A famous quote about learning is :

” Develop a passion for learning. If you do, you will never cease to grow.”

So Let’s begin.


Analyzing React Native

React Native has an alternative approach for cross-platform development. Traditionally, Cordova-based frameworks used WebView to render the whole application. In contrast, React Native applications run the JS code in a JavaScript VM based on JavaScriptCore. The application uses native JavaScriptCore on iOS and JavaScriptCore libs are bundled on an APK on Android.

In React Native, the communication between Native and JavaScript code is handled by a JavaScript Bridge. The source JS files are compiled into one single bundle file known as entry file. In development mode, the file is bundled on a local server and fetched by the application. For production, the application logic is usually bundled in a single file, usually “index.android.bundle” or “index.ios.bundle“. 

Similarly to Cordova, the bundle file is present in the assets folder and, as also happens with Cordova, we can assume React Native apps as containers that run JS code. This logic is implemented in the expo. Under certain limitations, Expo can run different business logic in a single application. At this moment, it’s fair to assume the entry-file as the core application logic.


Major Sections of Secure Mobile Application

Secure Mobile Application is divided into three sections :

  • Securing application to server connection
  • Securing local storage
  • Advanced integrity checks


1. Securing Application to Server Connection

Usually, smartphone apps communicate with the backend server via APIs. Insecure Communication is highlighted in the OWASP Mobile Top 10 at #3:

Mobile applications frequently do not protect network traffic. They may use SSL/TLS during authentication but not elsewhere. This inconsistency leads to the risk of exposing data and session IDs to interception. The use of transport security does not mean the app has implemented it correctly. To detect basic flaws, observe the phone’s network traffic. More subtle flaws require inspecting the design of the application and the applications configuration. – M3-Insecure Communication.

Starting from iOS 9 and Android Pie, SSL is required by default. We can enable cleartext traffic but it’s not recommended. To secure the connection further, we can pin our server certificates.


SSL Pinning in React Native

Apps are dependent on Certificate Authorities (CA) and Domain Name Servers (DNS) to validate domains for TLS. Unsafe certificates can be installed on a user device, thereby opening the device to a Man-in-the-Middle attack. SSL pinning can be used to mitigate this risk.

We use the fetch API or libraries like axios or frisbee to consume APIs in our React Native applications. However, these libraries don’t have support for SSL pinning. Let’s explore the available plugins:

  • react-native-ssl-pinning: this plugin uses OkHttp3 on Android and AFNetworking on iOS to provide SSL pinning and cookie handling. In this case, we will be using fetch from the library to consume APIs. For this library, we will have to bundle the certificates inside the app. Necessary error handling needs to be implemented in older apps to handle certificate expiry. The app needs to be updated with newer certificates before certificates expire. This library uses promises and supports multi-part form data.
  • react-native-pinch: this plugin is similar to react-native-ssl-pinning. We have to bundle certificates inside the app. This library supports both promises and callbacks.

To use HPKP (Http Public Key Pinning), we can consider these plugins:

  • react-native-cert-pinner: this plugin allows us to use public hashes to pin the server. Unlike the plugins above, we can use fetch and other utilities directly. The pinning occurs before native JS is run. Also, there is no requirement to define hashes in the request itself.
  • react-native-trustkit: this is a wrapper plugin for the iOS Trustkit library. This library is available for iOS only.


2. Securing Local Storage

Normally, we store data inside our application to achieve offline functionality. There are multiple ways to store persistent data in React Native. Async-storage, sqlite, pouchdb and realm are some of the methods to store data.

Insecure storage is highlighted at #2 in the OWASP Mobile Top 10:

Insecure data storage vulnerabilities occur when development teams assume that users or malware will not have access to a mobile device’s filesystem and subsequent sensitive information in data-stores on the device. Filesystems are easily accessible. Organizations should expect a malicious user or malware to inspect sensitive data stores. Usage of poor encryption libraries is to be avoided. Rooting or jailbreaking a mobile device circumvents any encryption protections. When data is not protected properly, specialized tools are all that is needed to view application data. – M2-Insecure Data Storage.

Let’s take a look at some plugins which add a layer of security to our application. Also, we will be exploring some plugins which use native security features Keychain and Keystore Access.


SQLite

SQLite is the most common way to store data. A very popular and open-source extension for SQLite encryption is SQLCipher. Data in SQLCipher is encrypted via 256 bit AES which can’t be read without a key. React Native has two libraries that provide SQLCipher:

  • react-native-sqlcipher-2 : this is a fork of react-native-sqlite-2. We can use pouchdb as an ORM provider with this library, so it’s an additional bonus.
  • react-native-sqlcipher-storage : this is a fork of react-native-sqlite-storage. The library has to be set up manually since it doesn’t seem to support react-native link. Interestingly, the library is based on the Cordova implementation.


Realm

Realm is a nice alternative database provider to React Native Apps. It’s much faster than SQLite and it has support for encryption by default. It uses the AES256 algorithm and the encrypted realm is verified using SHA-2 HMAC hash.


Keychain and Keystore Access

Both iOS and Android have native techniques to store secure data. Keychain services allows developers to store small chunks of data in an encrypted database. On Android, most plugins use the Android keystore system for API 23(Marshmallow) and above. For lower APIs, Facebook’s conceal provides the necessary crypto functions. Another alternative is to store encrypted data in shared preferences.

React Native has three libraries that provide secure storage along with biometric/face authentication:

  • React Native KeyChain: As the name implies, this plugin provides access to keychain/keystore. It uses Keychain (iOS), Keystore (Android 23+), and conceal. There is support for Biometric Auth. This plugin has multiple methods and options for both Android and iOS. However, it only allows the storage of the username & password.
  • React Native Sensitive Info: This plugin is similar to React Native Keychain. It uses Keychain (iOS) and shared preferences (Android) to store data. We can store multiple key-value pairs using this plugin.
  • RN Secure Storage: This plugin is similar to React Native Sensitive Info. It uses Keychain (iOS), Keystore (Android 23+), and Secure Preferences to store data. We can store multiple key-value pairs.


3. Advanced Integrity Checks


JailMonkey and SafetyNet

Rooted and jailbroken devices should be considered insecure by intent. Root privileges allow users to circumvent OS security features, spoof data, analyze algorithms, and access secured storage. As a rule of thumb, the execution of the app on a rooted device should be avoided.

JailMonkey allows React Native applications to detect root or jailbreak. Apart from that, it can detect if mock locations can be set using developer tools.

SafetyNet is an Android-only API for detecting rooted devices and boot loader unlocks. 

react-native-google-safetynet is a wrapper plugin for SafetyNet’s attestation API. It can be used to verify the user’s device.

Additionally, we can use react-native-device-info to check if an app is running in an emulator.


Protecting the Application Logic

Earlier in the article, we mentioned how the application logic in entry-file is available in plain sight. In other words, a third-party can retrieve the code, reverse-engineer sensitive logic, or even tamper with the code to abuse the app (such as unlocking features or violating license agreements).

Protecting the application logic is a recommendation in the OWASP Mobile Top 10. Specifically, the main concerns include code tampering:

Mobile code runs within an environment that is not under the control of the organization producing the code. At the same time, there are plenty of different ways of altering the environment in which that code runs. These changes allow an adversary to tinker with the code and modify it at will. — M8-Code Tampering. “

And reverse engineering:

Generally, most applications are susceptible to reverse engineering due to the inherent nature of code. Most languages used to write apps today are rich in metadata that greatly aides a programmer in debugging the app. This same capability also greatly aides an attacker in understanding how the app works. — M9-Reverse Engineering.”

Let’s highlight two different strategies to address this risk.


Hermes

Facebook introduced Hermes with the react-native 0.60.1 release. Hermes is a new JavaScript Engine optimized for mobile apps. Currently, it is only available with Android and it’s usage is optional. Hermes can be used in the project with react-native 0.60.4 by changing the enableHermes flag in build.gradle file.

Its key benefits are improved start-up time, decreased memory usage, and smaller app size. One of the strategies that Hermes uses to achieve this is precompiling JavaScript to bytecode.

Let’s look at a real example. We assume that our entry-file is the one found below:

const {createDecipheriv, createCipheriv, randomBytes} = require('crypto');
const key = Buffer.from('60adba1cf391d89a3a71c72a615cbba8', 'hex');
const algorithm = 'aes-128-cbc';
const softwareVersion = '2.0';
module.exports.createKey = function(userId, expireDate) {
  const payload = {
    userId,
    expireDate,
    softwareVersion
  };
  const json = Buffer.from(JSON.stringify(payload), 'utf8');
  const iv = randomBytes(16);
  const cipher = createCipheriv(algorithm, key, iv);
  let encoded = cipher.update(json);
  encoded = Buffer.concat([encoded, cipher.final()]);
  const joined = iv.toString('hex') + ';' + encoded.toString('hex');
  return Buffer.from(joined, 'utf8').toString('base64');
}
module.exports.validateLicense = function(license, userId) {
  const licenseFields = Buffer.from(license, 'base64').toString('utf8');
  const fields = licenseFields.split(';');
  const iv = Buffer.from(fields[0], 'hex');
  const data = Buffer.from(fields[1], 'hex');
  const decipher = createDecipheriv(algorithm, key, iv);
  let decoded = decipher.update(data);
  decoded = Buffer.concat([decoded, decipher.final()]);
  const result = JSON.parse(decoded);
  if (result.userId != userId) {
    throw new Error('Wrong user');
  }
  if (new Date(result.expireDate) < new Date()) {
    throw new Error('Expired license');
  }
  if (result.softwareVersion != softwareVersion) {
    throw new Error('This license is not valid for this program version');
  }
  return result;
}

After Hermes compiles this file, the resulting bytecode can easily be decompiled using hbcdump and, among the decompiled code, we find some easy to read code look like:

s0[ASCII, 0..-1]: 
s1[ASCII, 0..2]: 2.0
s2[ASCII, 3..34]: 60adba1cf391d89a3a71c72a615cbba8
s3[ASCII, 35..35]: ;
s4[ASCII, 36..50]: Expired license
s5[ASCII, 71..120]: This license is not valid for this program version
s6[ASCII, 121..130]: Wrong user
s7[ASCII, 133..143]: aes-128-cbc
s8[ASCII, 143..148]: crypto
s9[ASCII, 154..159]: global
s10[ASCII, 160..165]: base64
s11[ASCII, 166..168]: hex
s12[ASCII, 177..180]: utf8
i13[ASCII, 50..56] #C765D706: exports
i14[ASCII, 56..70] #FF849242: softwareVersion
i15[ASCII, 127..132] #6FE51CD4: userId
i16[ASCII, 147..154] #1E019520: toString
i17[ASCII, 167..176] #68A06D42: expireDate
i18[ASCII, 173..176] #CD347266: Date
i19[ASCII, 181..186] #5AA7C487: Buffer
i20[ASCII, 186..196] #FD81EB01: randomBytes
i21[ASCII, 196..200] #0EC469F8: split
i22[ASCII, 201..205] #9102A3D0: Error
i23[ASCII, 205..211] #EB75CA32: require
i24[ASCII, 212..215] #971CE5C7: JSON
i25[ASCII, 216..221] #CB8DFA65: concat
i26[ASCII, 222..235] #96C7181F: createCipheriv
i27[ASCII, 235..249] #D60B6B51: validateLicense
i28[ASCII, 250..265] #723D6A80: createDecipheriv
i29[ASCII, 266..274] #01D3AE7D: createKey
i30[ASCII, 275..279] #47993A63: final
i31[ASCII, 280..283] #EAF03666: from
i32[ASCII, 283..288] #2A322C6E: module
i33[ASCII, 289..293] #958EDB02: parse
i34[ASCII, 294..302] #807C5F3D: prototype
i35[ASCII, 303..311] #8D1543BD: stringify
i36[ASCII, 312..317] #60396F4B: update

Function<global>0(1 params, 15 registers, 4 symbols):
Offset in debug table: src 0x0, vars 0x0
license.js[1:1]
    CreateEnvironment r0
    GetGlobalObject   r1
    TryGetById        r4, r1, 1, "require"
    LoadConstUndefined r3
    LoadConstString   r2, "crypto"
    Call2             r2, r4, r3, r2
    GetByIdShort      r3, r2, 2, "createDecipheriv"
    StoreToEnvironment r0, 0, r3
    GetByIdShort      r3, r2, 3, "createCipheriv"
    StoreToEnvironment r0, 1, r3
    GetByIdShort      r2, r2, 4, "randomBytes"
    StoreToEnvironment r0, 2, r2
    TryGetById        r5, r1, 5, "Buffer"
    GetByIdShort      r4, r5, 6, "from"
    LoadConstString   r3, "60adba1cf391d89a3"...
    LoadConstString   r2, "hex"
    Call3             r2, r4, r5, r3, r2
    StoreToEnvironment r0, 3, r2
    TryGetById        r2, r1, 7, "module"
    GetByIdShort      r3, r2, 8, "exports"
    CreateClosure     r2, r0, 1
    PutById           r3, r2, 1, "createKey"
    TryGetById        r1, r1, 7, "module"
    GetByIdShort      r1, r1, 8, "exports"
    CreateClosure     r0, r0, 2
    PutById           r1, r0, 2, "validateLicense"
    Ret               r0

So, while Hermes introduces a certain degree of complexity to the entry-file code, it doesn’t actually conceal the code nor do anything to prevent code tampering, which means that it won’t stop an attacker ⁠— let’s not forget that this is not even the purpose of Hermes.

And this leads us to an approach that obfuscates React Native’s JavaScript source code to effectively mitigate the risk of code tampering and reverse engineering: Jscrambler.


Jscrambler

Jscrambler provides a series of layers to protect JavaScript. Unlike most tools that only include (basic) obfuscation, Jscrambler provides three security layers:

  • Polymorphic JavaScript & HTML5 obfuscation
  • Code locks (domain, OS, browser, time frame)
  • Self-defending (anti-tampering & anti-debugging)

By protecting the source code of React Native apps with Jscrambler, the resulting code is highly obfuscated, as can be observed below:

On top of this obfuscation, there’s a Self-Defending layer that provides anti-debugging and anti-tampering capabilities and enables setting countermeasures like breaking the application, deleting cookies, or destroying the attacker’s environment.

That’s all about in this article.


Conclusion

In this article, We learned how to secure Mobile applications in React Native. We discussed about Mobile application security related areas and techniques for React Native . It provides an overview of techniques to help to secure the React Native application. It’s then crucial to create a threat model , and depending on the application’s use case, employ the required measures to ensure that the application is properly secured.

Thanks for reading ! I hope you enjoyed and learned about the Mobile Application Security concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – 7 Effective Patterns To Improve Development Experience

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native 7 effective simple patterns which helps to improve our react native experience during development mode. We will discuss about react native 7 effective simple patterns one by one.

  • Keep most of components stupid
  • Rely on callbacks
  • Keep navigation stack away from views
  • Keep callbacks chained together
  • Keep reducers simple and declarative
  • Keep business logic out of Reducers
  • Keep platform-specific components to a minimum

A famous quote about Learning is :

Tell me and I forget, teach me and I may remember, involve me and I learn.

So Let’s begin.


Pattern 1 : Keep most of components stupid

  • This is true for any React application. Our views and components should rely on props and callbacks while Container (smart) components should rely on state.
  • We recommend using Redux, but in some applications we can get away using plain old setState. MobX is a great alternative too.


Pattern 2 : Rely on callbacks

  • When we learn how to code iOS apps in Swift, we taught to use the delegate pattern to decouple a view from its behavior. In React Native, the same effect can be achieved via callbacks.
  • Callbacks are simply Arrow Functions which can be passed to a component. The component has the responsibility to execute them, but doesn’t need to know what it’s actually doing.
  • Most component should not have any behavior. Expose simple callbacks, they are like the public API of our components. We should know when they’ll be executed by reading their names. If we are developing an e-commerce app, for example, names like onSelectProduct or onProductAddedToShoppingCart are very declarative.
  • When deciding whether to expose a callback or not, every time a component has some kind of user interaction, ask ourself this:
    Is this interaction only important for this particular component, or can it trigger changes in another part of the application? ” If the latter is our answer, then we should expose a callback.


Pattern 3 : Keep navigation stack away from views

  • For this particular application, we were able to migrate from React Native’s default Navigator, to NavigationExperimental, to React Navigation. Those changes involved a few lines of code.
  • The idea is simple: Screens and Views are not the same. Our views should not have any knowledge of the Navigation Stack while Screens (or Routes, depending on what name we prefer) must know how to navigate and how to communicate with the Navigation Bar / TabBar. With this approach, our screens will simply wrap the actual Views with navigation-aware things, For example:
const FavoritesView = ({ favorites, onSelectFavorite }) =>    

const FavoritesScreen = ({ navigation }) =>
   navigation.push('FAVORITE', {{ favorite: favorite }})}/>

const NavigationStack = StackNavigator({
  FAVORITES: FavoritesScreen,
  FAVORITE: FavoriteScreen
})
  • As we can see, FavoritesView simply exposes an ‘onSelectFavorite’ callback and doesn’t care about what it actually does. FavoritesScreen uses that callback to tell the navigator to navigate to another screen. Therefore, this gives us the flexibility to replace the way our navigation stack works and provides a nice separation.


Pattern 4 : Keep callbacks chained together

  • A very common pattern is to inject behavior into callbacks within Higher order Components (that’s what Redux’s mapStateToProps actually does), but many people forget that a public callback may be used in another part of the app (an outer component, for example).
  • Every time one of our views exposes a callback which may be used in another part of our application (such as, mapStateToProps), first invoke the actual callback passed on props. This enables us to, for example, Navigate to a screen and also fetch some information to feed the next view.
const mapDispatchToProps = (dispatch, props) => ({
   onSelectFavorite: (favorite) => {
     props.onSelectFavorite(favorite);
     dispatch(fetchFavoriteInfo(favorite.id));
   }
})

const mapStateToProps = (state) => ({
   favorites: state.favorites
})

export default connect(mapStateToProps, mapDispatchToProps)(FavoritesView)
  • Following the previous example, if FavoritesScreen told FavoritesView to navigate to the FavoriteScreen when selecting a Favorite, Redux would honor that, but also invoke some Redux actions.
  • As we may see, every realm knows how to handle its stuff: Screens know how to navigate, Connected Views know how to handle redux actions and Views are dumb, stateless and rely on their props.


Pattern 5 : Keep reducers simple and declarative

  • Any developer should be able to view your reducer’s code and understand what it’s doing. In most cases, having one function per action type can increase readability. For example:
const clear = (favoriteId) => state => ...
const fetching = (favoriteId) => state => ...
const finishFetching = (favoriteId, favorite) => state => ...

export default (state = {}, action) => {
    switch (action.type) {
        case 'CLEAR_FAVORITE':
            return clear(action.favoriteId)(state);
        case 'FETCHING_FAVORITE':
            return fetching(action.favoriteId)(state);
        case 'FINISH_FETCHING_FAVORITE':
            return finishFetching(action.favoriteId, action.favorite)(state);
        default:
            return state;
    }
}
  • Composing reducer functions with many one-line functions can give us greater flexibility and code reuse.


Pattern 6 : Keep business logic out of Reducers

  • Redux store is not part of business model, it’s a View Model. Treat it like such. Reducer should only impact the store with changes, and we need to be highly confident of them. The less knowledge Reducers have of own business rules, the simpler they’ll become.
  • It’s not the best approach, but a better one to put business logic in action creators, specially if we use a middleware like Thunk. Sagas and Epics are great too.


Pattern 7 : Keep platform-specific components to a minimum

  • Every platform has its own Design/UX language and in many cases we have to write different versions of a component. Remember that React Native’s aim is learn once, write anywhere, but first try not to rush into writing platform-specific components.
  • In many cases, simple Style-changes and conditional operators are enough. we’ve created a simple helper function called platformSpecific which allows me to set styles according to a platform.It’s a really simple function, but incredibly useful. For example :
const platformSpecific = ({ios, android}) => (Platform.OS == ‘ios’) ? ios : android

That’s all about in this article.


Conclusion

In this article, We understood the React Native 7 effective simple patterns with the below summary :

  • Keep most of the components simple and dumb
  • Expose callback
  • Keep navigation stack separate from views
  • Keep callbacks chained together
  • Reducer code should be simple and declarative form
  • Application business logic should be separated from Reducer
  • Platform specific components should be used minimum. Use common components code for different platforms if possible.

Thanks for reading ! I hope you enjoyed and learned about the React Native 7 effective simple patterns. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – An Overview Of React Native Foundation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native Foundation. We will discuss  about react native core concepts through examples. 

A famous quote about learning is :

I am still learning.

So Let’s begin.


What Is React Native ?

React Native is like React, but it uses native components instead of web components as building blocks. So to understand the basic structure of a React Native app, we need to understand some of the basic React concepts, like JSX, components, state, and props.

If we already know React, we still need to learn some React-Native-specific stuff, like the native components.

Let’s do this thing.

Hello World

import React from 'react';
import { Text, View } from 'react-native';

function HelloWorldApp() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>
        Hello, world!
      </Text>
    </View>
  );
}
export default HelloWorldApp;

What’s going on here?

  1. First of all, we need to import React to be able to use JSX, which will then be transformed to the native components of each platform.
  2. On line 2, we import the Text and View components from react-native.

Then we find the HelloWorldApp function, which is a functional component and behaves in the same way as in React for the web. This function returns a View component with some styles and aText as its child.

The Text component allows us to render a text, while the View component renders a container. This container has several styles applied, let’s analyze what each one is doing.

The first style that we find is flex: 1, the flex prop will define how our items are going to “fill” over the available space along your main axis. Since we only have one container, it will take all the available space of the parent component. In this case, it is the only component, so it will take all the available screen space.

The following style is justifyContent: “center”. This align children of a container in the center of the container’s main axis and finally we have alignItems: “center”, which align children of a container in the center of the container’s cross axis.React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. importfromclass, and extends in the example above are all ES2015 features.

The other unusual thing in this code example is Hello world!

This is JSX – a syntax for embedding XML within JavaScript. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like <div> or <span> you use React components. In this case, <text> is a Core Component that displays some text and View is like the <div> or <span>.


React Native Fundamentals

React Native runs on React, a popular open source library for building user interfaces with JavaScript. To make the most of React Native, it helps to understand React itself.

We’re going to cover the core concepts behind React native :

  • Components
  • JSX
  • props
  • state


Components

So HelloWorldApp example code is defining HelloWorldApp, a new Component. When we’re building a React Native app, we’ll be making new components a lot. Anything we see on the screen is some sort of component.


JSX

React and React Native use JSX, a syntax that lets we write elements inside JavaScript like so: <Text>Hello, I am your cat!</Text>.

Because JSX is JavaScript, we can use variables inside it. Here we are declaring a name for the cat, name, and embedding it with curly braces inside <Text>.

import React from 'react';
import { Text } from 'react-native';

const Cat = () => {
  const name = "Maru";
  return (
    <Text>Hello, I am {name}!</Text>
  );
}

export default Cat;

Because JSX is included in the React library, it won’t work if we don’t have import React from 'react' at the top of our file!


Props

Most components can be customized when they are created, with different parameters. These creation parameters are called props.

Our own components can also use props. This lets us make a single component that is used in many different places in our app, with slightly different properties in each place. Refer to props.{NAME} in our functional components or this.props.{NAME} in our class components. Here’s an example:

import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ center: { alignItems: 'center' } }) function Greeting(props) { return ( <View style={styles.center}> <Text>Hello {props.name}!</Text> </View> ); } function LotsOfGreetings() { return ( <View style={[styles.center, {top: 50}]}> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> </View> ); } export default LotsOfGreetings;

Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX. The power to do this is what makes React so cool.

The other new thing going on here is the View component. A View is useful as a container for other components, to help control style and layout.

With props and the basic TextImage, and View components, we can build a wide variety of static screens. To learn how to make our app change over time, we need to learn about State.


State

Unlike props that are read-only and should not be modified, the state allows React components to change their output over time in response to user actions, network responses and anything else. Here’s an example:

import React, { Component } from 'react' import { StyleSheet, TouchableOpacity, Text, View, } from 'react-native' class App extends Component { state = { count: 0 } onPress = () => { this.setState({ count: this.state.count + 1 }) } render() { return ( <View style={styles.container}> <TouchableOpacity style={styles.button} onPress={this.onPress} > <Text>Click me</Text> </TouchableOpacity> <View style={styles.countContainer}> <Text> You clicked { this.state.count } times </Text> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, button: { alignItems: 'center', backgroundColor: '#DDDDDD', padding: 10, marginBottom: 10 } }) export default App;

In this example,

  1. First of all, we need to import React to be able to use JSX, which will then be transformed to the native components of each platform.
  2. On line 2, we import the StyleSheet , TouchableOpacity , Text and View components from react-native
  3. In next line , we defines a new class  App which extends from React Component .This block of code defines the components that represent the user interface.
  4. After that, we initialize  our app state variable count  to 0 inside App class using  state  variable.
  5. After that we create  onPress()  method where count  is incremented by 1 and count   value is set in  setState()  method.
  6. After that Inside render()  method that returns a react element , includes:
    • A  return()  that returns the result of layout and UI components.
    • A container View  that supports the layout accessibility controls. It is a fundamental component for building the UI.
    • A  TouchableOpacity  wrapper is used to reduce the opacity of button. Here, onPress method is called using onPress props.
    • A React component Text  for displaying text.
    • A property style  used for styling the components using  StyleSheet class.
    • styles   is used to design individual components.
  7. After that, the  StyleSheet  class creates the style object that controls the layout and appearance of components. It is similar to Cascading Style Sheets (CSS) used on the Web.

That’s all about in this article.


Conclusion

In this article, We have discussed about React Native Foundations Concepts like Components,Props and State through example explanations. So we conclude that

  • Components : Everything is component in React Native.The way in which you create a new component.
  • Props : Most components can be customized when they are created, with different parameters. These creation parameters are called props.
  • State : State allows React components to change their output over time in response to user actions, network responses and anything else.

Thanks for reading ! I hope you enjoyed and learned about the React Native Foundation. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How React Native Works Internally?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native Internal architecture. This article will discuss React Native internal work flow.

A famous quote about learning is :

” Try to learn something about everything and everything about something. “

So, Let’s Start.

Overview

” React Native is a framework which allows developers to build native apps using javascript.”

So What about Cordova Platform and why would anyone want to use React Native?

The Primary difference between React Native and Cordova based app is that

  • Cordova based apps run inside a Web View. 
  • React Native apps renders using Native View.

React Native Application have direct access to all the native APIs and views offered by the underlying mobile OS. React Native Applications have the same feel and performance as that of a native application.

We can assume that React native might be compiling JS code into respective native code directly. But this would be really hard to achieve since Java and Objective C are strongly typed languages while Javascript is not!

React Native does something much more clever.Essentially React Native uses a set of React components, where each component represents the corresponding native views and components.

For example, a native TextInput will have a corresponding React Native component which can be directly imported into the JS code and used like any other React component. Hence, the developer will be writing the code just like for any other React Web app but the output will be a native application.

To understand this, let us take a look at the architecture and Threading model and how React Native works internally.


Architecture

React Native uses similar architecture for iOS and Android platform. There are three parts to React Native Platform :


1. Native Code/Modules

Most of the native code in case of iOS is written in Objective C or Swift, while in the case of Android it is written in Java. But for writing our React Native app, we would hardly ever need to write native code for iOS or Android.


2. JavaScript VM

  • The JS Virtual Machine that runs all our JavaScript code. On iOS/Android simulators and devices React Native uses JavaScriptCore, which is the JavaScript engine that powers Safari. JavaScriptCore is an open source JavaScript engine originally built for WebKit. 
  • In case of iOS, React Native uses the JavaScriptCore provided by the iOS platform. It was first introduced in iOS 7 along with OS X Mavericks.
  • In case of Android, React Native bundles the JavaScriptCore along with the application. This increases the app size. Hence the Hello World application of RN would take around 3 to 4 megabytes for Android.
  • In case of Chrome debugging mode, the JavaScript code runs within Chrome itself (instead of the JavaScriptCore on the device) and communicates with native code via WebSocket. Here, it will use the V8 engine. This allows us to see a lot of information on the Chrome debugging tools like network requests, console logs, etc.

3. React Native Bridge

React Native bridge is a C++/Java bridge which is responsible for communication between the native and Javascript thread. A custom protocol is used for message passing.


Threading Models

When a React Native application is launched, it spawns up the following threading queues:


1. Main Thread (Native Queue)

  • Main thread gets spawned when application launches. It loads the app and starts the JS thread to execute the JavaScript code.
  • The Native thread also listens to the UI events like ‘press’, ‘touch’ etc. These events are then passed to the JS thread via RN Bridge.
  • Once the Javascript loads, the JS thread sends the information on what needs to be rendered onto the screen.This information is used by a shadow node thread to compute the layout.
  • The Shadow thread is basically like mathematical engine which finally decides on how to compute the view positions.
  • These instructions are then passed back to the main thread to render the view.


2. JavaScript Thread (JS Queue)

  • The Javascript Queue is the thread queue where main bundled JS thread runs. 
  • The JS thread runs all the business logic, i.e., the code we write in React Native. 


3. Custom Native Modules

  • Apart from the threads spawned by React Native, we can also spawn threads on the custom native modules to build to speed up the performance of the application.
  • For Example – Animations are handled in React Native by a separate native thread to offload the work from the JS thread.

That’s all about in this article.


Conclusion

In this article, We understood about React Native Internal Work Flow. We conclude that React Native work flow based on the threading models and process involved between different threads. We can separate React Native into three Parts :

  • React Native-Native Side
  • React Native -JS Side
  • React Native – Bridge

This is also called “3 Parts of React Native”.

Thanks for reading ! I hope you enjoyed and learned about Internal architecture,Threading Models and Process involved in React Native . Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version