Blog

React Native – How To Use Hooks In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Use Hooks In React Native ?).

In this article, we will understand about how to use Hooks in react native. Hooks are specially-implemented functions that let us add functionality to React components beyond just creating and returning React elements. This article demonstrates the built-in hooks usage in react native application.

A famous quote about learning is :

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

So Let’s begin.


React Hooks

” React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you “hook into” React state and lifecycle features from function components. (They do not work inside class components.)”

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. It mainly uses to handle the state and side effects in react functional component. React Hooks are a way to use stateful functions inside a functional component. Hooks don’t work inside classes — they let you use React without classesReact provides a few built-in Hooks like useState and useEffect. The React hooks do :

  • Best practices
  • Easy to under understand
  • Easy to test
  • Increases the performance and so on.


Rules and Linting

Hooks aren’t regular functions; they have to be written in a certain way. To dive deeper into this topic, check out:

ReactJS – How to Effectively Think In React Hooks ?

When using hooks, we typically want to use eslint and the react-hooks plugin. Hooks are powerful, but can be unintuitive at first, and this tool catches a lot of mistakes before we ever run our code.


In-built React Hooks APIs

We’ll look at the following built-in hooks in more detail:

  • useState – Persist state within a component function
  • useReducer – Similar to useState, but for state that involves multiple sub-values
  • useEffect – Perform side effects within our component functions
  • useRef – Wrap a mutable value


1. useState

The useState hook lets us “remember” a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.


API

The useState hook takes a single argument, our initial state, and returns an array containing two elements:

  • state – the current state
  • setState – a function to update our state

Syntax –  const [state, setState] = useState(initialValue)


Example

In this example, we’ll use useState to append to an array.

The useState hook can store any type of value: a number, a string, an array, an object, etc.

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

const randomDiceRoll = () => Math.floor(Math.random() * 6) + 1

export default function App() {
  const [diceRolls, setDiceRolls] = useState([])

  return (
    <View>
      <Button
        title="Roll dice!"
        onPress={() => {
          setDiceRolls([...diceRolls, randomDiceRoll()])
        }}
      />
      {diceRolls.map((diceRoll, index) => (
        <Text style={{ fontSize: 24 }} key={index}>
          {diceRoll}
        </Text>
      ))}
    </View>
  )
}

The result of above example is displayed below :


Updating mutable state values

Note how when we call setDiceRoll, we’re not pushing the integer returned from randomDiceRoll() into the diceRolls array. Instead, we return a new array containing the destructured diceRolls array and the newly randomized dice roll. Why?

Hooks can tell React to re-run our component function and update the UI. The useState hook tells React to re-run our component function whenever we call setDiceRolls with a different value. Internally, useState then compares the current value of diceRolls with the value we passed to setDiceRolls using ===. If we’re using a mutable value like an array, and we only change its contents, useState won’t detect that change and won’t tell React to re-run our component function. This will result in our UI displaying old/stale data. To avoid this problem we need to create a new array, so that useState will detect that our data changed and display the newest data.


2. useReducer

The useReducer hook is similar to useState, but gives us a more structured approach for updating complex values.

We typically use useReducer when our state has multiple sub-values, e.g. an object containing keys that we want to update independently.


API

The useReducer hook requires 2 arguments, and has an optional 3rd argument:

  • reducer – a pure function that takes a state and an action, and returns a new state value based on the action
  • initialState – any initial state value, just like useState
  • initializer (optional) – a function called to lazily instantiate the initialState (this is uncommon)

The useReducer hook returns the current state, and a dispatch function to update the state.


Example

In this example, we store both a first and last name in a single state object with useReducer.

When we type a new first name, dispatch is called with { type: 'first', value: text } as its argument. This argument gets passed to the reducer as action. Then the reducer follows the switch case logic case 'first' and returns the new state: the current last name (from ...state) and the new first name contained in the action as action.value.

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

function reducer(state, action) {
  switch (action.type) {
    case 'first':
      return { ...state, first: action.value }
    case 'last':
      return { ...state, last: action.value }
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, { first: '', last: '' })

  return (
    <View>
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="First"
        value={state.first}
        onChangeText={(text) => {
          dispatch({ type: 'first', value: text })
        }}
      />
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="Last"
        value={state.last}
        onChangeText={(text) => {
          dispatch({ type: 'last', value: text })
        }}
      />
      <Text style={{ fontSize: 32 }}>
        Hello {state.first} {state.last}
      </Text>
    </View>
  )
}

The result of above example is displayed below :


3. useEffect

We use the useEffect hook to call functions with side effects within our components.


API

The useEffect hook takes 2 arguments:

  • callback – a function with side effects
  • dependencies – an optional array containing dependency values

When our component function runs, the callback will be called if any dependencies have changed since the last time the component function ran.


Example

In this example, we’ll log to the console any time the count is a multiple of 3. The callback is called every time the countEvery3 changes, since countEvery3 is listed as a dependency.

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)
  const countEvery3 = Math.floor(count / 3)

  useEffect(() => {
    console.log(countEvery3)
  }, [countEvery3])

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


Undefined or empty dependency array

If the dependency array is empty or undefineduseEffect will have a different behavior:

  • [] – the callback is called only once, right after the component renders for the first time.
  • undefined – the callback is called on every component render (every time the component function runs).


undefined dependencies

Here the dependency array is undefined, so our callback will run every time our component function runs, e.g. any time we click the button and useState tells our component to re-run.

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    console.log('Incremented!')
  })

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


Empty dependencies

Here the dependency array is empty, so our callback will only run once (and therefore only log one time).

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    console.log('Only once!')
  }, [])

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


4. useRef

With useRef, we can create and update a single mutable value that exists for the lifetime of the component instance.

After assigning the ref to a variable, we use .current to access the mutable value.


Example

In this example, we store the return value of setInterval, which is an interval id, so that we can later call clearInterval.

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

export default function App() {
  const intervalRef = useRef()
  const [count, setCount] = useState(0)

  useEffect(() => {
    intervalRef.current = setInterval(
      () => setCount((count) => count + 1),
      1000
    )

    return () => {
      clearInterval(intervalRef.current)
    }
  }, [])

  return (
    <View>
      <Text style={{ fontSize: 120 }}>{count}</Text>
      <Button
        title="Stop"
        onPress={() => {
          clearInterval(intervalRef.current)
        }}
      />
    </View>
  )
}

The result of above example is displayed below :


5. Custom Hooks

We can compose built-in hooks to create new ones. We should still use the use prefix for our function name.


Example

import React, { useState, useEffect, useRef } from 'react'
import { Text } from 'react-native'

function useInterval(callback, delay) {
  const savedCallback = useRef()

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback
  }, [callback])

  // Set up the interval.
  useEffect(() => {
    if (delay !== null) {
      let id = setInterval(() => {
        savedCallback.current()
      }, delay)
      return () => clearInterval(id)
    }
  }, [delay])
}

export default function App() {
  const [count, setCount] = useState(0)

  useInterval(() => {
    setCount(count + 1)
  }, 1000)

  return <Text style={{ fontSize: 120 }}>{count}</Text>
}

That’s all about in this article.


Conclusion

In this article, We understood about how to use Hooks in React Native. This article demonstrated In-built Hooks APIs Usage with examples in React Native application.

Thanks for reading ! I hope you enjoyed and learned about the Hook 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 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 !!???

iOS – How To Prepare UI To Run In The Background In iOS ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Prepare UI To Run In The Background In iOS ?).

In this article, we will learn about how to prepare UI to run in the background in iOS. We will discuss how to prepare our app to be suspended.

A famous quote about Learning is :

” You don’t understand anything until you learn it more than one way. “

So Let’s begin.


Overview

Apps move to the background state for many reasons. When the user exits a foreground app, that app moves to the background state briefly before UIKit suspends it. The system may also launch an app directly into the background state, or move a suspended app into the background, and give it time to perform important tasks.

When our app is in the background in iOS, it should do as little as possible, and preferably nothing. If our app was previously in the foreground, use the background transition to stop tasks and release any shared resources. If our app enters the background to process an important event, process the event and exit as quickly as possible.

All state transitions result in UIKit sending notifications to the appropriate delegate object:

  • In iOS 13 and later—A UISceneDelegate object.
  • In iOS 12 and earlier—The UIApplicationDelegate object.

We can support both types of delegate objects, but UIKit always uses scene delegate objects when they are available. UIKit notifies only the scene delegate associated with the specific scene that is entering the background.


Quiet App upon Deactivation

The system deactivates apps for several reasons. When the user exits the foreground app, the system deactivates that app immediately before moving it to the background. The system also deactivates apps when it needs to interrupt them temporarily—for example, to display system alerts. In the case of a system panel, the system reactivates the app when the user dismisses the panel.

During deactivation, UIKit calls one of the following methods of our app:

  • For apps that support scenes—The sceneWillResignActive(_:) method of the appropriate scene delegate object.
  • For all other apps—The applicationWillResignActive(_:) method of the app delegate object.

Use deactivation to preserve the user’s data and put our app in a quiet state by pausing all major work; specifically:

  • Save user data to disk and close any open files.
  • Suspend dispatch and operation queues.
  • Don’t schedule any new tasks for execution.
  • Invalidate any active timers.
  • Pause gameplay automatically.
  • Don’t commit any new Metal work to be processed.
  • Don’t commit any new OpenGL commands.


Release Resources upon Entering the Background

When our app transitions to the background, release memory and free up any shared resources our app is holding. For an app transitioning from the foreground to the background, freeing up memory is especially important. The foreground has priority over memory and other system resources, and the system terminates background apps as needed to make those resources available. Even if our app wasn’t in the foreground, perform checks to ensure that it consumes as few resources as possible.

Upon entering the background, UIKit calls one of the following methods of our app:

  • For apps that support scenes—The sceneDidEnterBackground(_:) method of the appropriate scene delegate object.
  • For all other apps—The applicationDidEnterBackground(_:) method of the app delegate object.

During a background transition, perform as many of the following tasks as makes sense for our app:

  • Discard any images or media that we read directly from files.
  • Discard any large, in-memory objects that we can recreate or reload from disk.
  • Release access to the camera and other shared hardware resources.
  • Hide sensitive information (such as passwords) in our app’s user interface.
  • Dismiss alerts and other temporary interfaces.
  • Close connections to any shared system databases.
  • Unregister from Bonjour services and close any listening sockets associated with them.
  • Ensure that all Metal command buffers have been scheduled.
  • Ensure that all OpenGL commands, we previously submitted have finished.

We don’t need to discard named images that we loaded from our app’s asset catalog. Similarly, we don’t need to release objects that adopt the NSDiscardableContent protocol or that we manage using an NSCache object. The system automatically handles the cleanup of those objects.

Make sure our app is not holding any shared system resources when it transitions to the background. If it continues accessing resources like the camera or a shared system database after transitioning to the background, the system terminates our app to free up that resource. If we use a system framework to access a resource, check the framework’s documentation for guidelines about what to do.


Prepare UI for the App Snapshot

After our app enters the background and our delegate method returns, UIKit takes a snapshot of our app’s current user interface. The system displays the resulting image in the app switcher. It also displays the image temporarily when bringing our app back to the foreground.

Our app’s UI must not contain any sensitive user information, such as passwords or credit card numbers. If our interface contains such information, remove it from our views when entering the background. Also, dismiss alerts, temporary interfaces, and system view controllers that obscure our app’s content. The snapshot represents our app’s interface and should be recognizable to users. When our app returns to the foreground, we can restore data and views as appropriate.

For apps that support state preservation and restoration, the system begins the preservation process shortly after our delegate method returns. Removing sensitive data also prevents that information from being saved in our app’s preservation archive.


Respond to Important Events in the Background

Apps don’t normally receive any extra execution time after they enter the background. However, UIKit does grant execution time to apps that support any of the following time-sensitive capabilities:

  • Audio communication using AirPlay, or Picture in Picture video.
  • Location-sensitive services for users.
  • Voice over IP.
  • Communication with an external accessory.
  • Communication with Bluetooth LE accessories, or conversion of the device into a Bluetooth LE accessory.
  • Regular updates from a server.
  • Support for Apple Push Notification service (APNs).

Enable the Background Modes capability in Xcode if our app supports background features.

That’s all about in this article.


Conclusion

In this article, We understood how to prepare UI to run in the Background in iOS. We also discussed how to prepare our app to be suspended.

Thanks for reading ! I hope you enjoyed and learned about UI Preparation concepts during Background in iOS. 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.

You can find Other articles of CoolmonkTechie as below link :

You can also follow other website and tutorials of iOS 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 !!???

A Short Note – How To Control Component Size In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Control Component Size In React Native ?).

In this note series, we will learn how to control component size in React Native. A component’s height and width determine its size on the screen.

So Let’s begin.


Fixed Dimensions

The general way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless and represent density-independent pixels.

Height and Width

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

const FixedDimensionsBasics = () => {
    return (
      <View>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} />
        <View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} />
      </View>
    );
};

export default FixedDimensionsBasics;

Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.

The Preview of the above example is :


Flex Dimensions

We use flex in a component’s style to have the component expand and shrink dynamically based on available space. Normally we will use flex: 1, which tells a component to fill all available space, shared evenly amongst other components with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.

A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.

Flex Dimensions

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

const FlexDimensionsBasics = () => {
    return (
      // Try removing the `flex: 1` on the parent View.
      // The parent will not have dimensions, so the children can't expand.
      // What if you add `height: 300` instead of `flex: 1`?
      <View style={{flex: 1}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}} />
        <View style={{flex: 2, backgroundColor: 'skyblue'}} />
        <View style={{flex: 3, backgroundColor: 'steelblue'}} />
      </View>
    );
};

export default FlexDimensionsBasics;

The Preview of the above example is :


Conclusion

In this note series, we understood how to control component size in React Native. This note series showed Fixed Dimensions and Flex Dimensions to control the component size in react native.

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

Please follow and subscribe to the 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, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – How To Prepare UI To Run In The Foreground In iOS ?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Prepare UI To Run In The Foreground In iOS ?).

In this note series, we will learn about how to prepare UI to run in the foreground in iOS. This note series shows how to configure our app to appear on-screen.

So Let’s begin.


Overview

We use foreground transitions to prepare our app’s UI to appear on-screen. An app’s transition to the foreground is usually in response to a user’s action. For example, when the user taps the app’s icon, the system launches the app and brings it to the foreground. We use a foreground transition to update our app’s UI, gain resources, and start the services we need to handle user requests.

All state transitions result in UIKit sending notifications to the delegate object:

  • In iOS 13 and later—A UISceneDelegate object.
  • In iOS 12 and earlier—The UIApplicationDelegate object.

We can support both types of delegate objects, but UIKit always uses scene delegate objects when they are available. UIKit notifies only the scene delegate associated with the specific scene that is entering the foreground.


Update Our App’s Data Model when Entering the Foreground

At launch time, the system starts our app in the inactive state before transitioning it to the foreground. We use our app’s launch-time methods to perform any work needed. UIKit moves our background app to the inactive state by calling one of the following methods:

  • For apps that support scenes — The sceneWillEnterForeground(_:) method of the scene delegate object.
  • For all other apps — The applicationWillEnterForeground(_:) method.

When transitioning from the background to the foreground, we use these methods to load resources from disk and fetch data from the network.


Configure User Interface and Initial Tasks at Activation

The system moves our app to the active state immediately before displaying the app’s UI. Activation is a good time to configure our app’s UI and runtime behavior; specifically:

  • Show our app’s windows if needed.
  • Change the currently visible view controller, if needed.
  • Update the data values and state of views and controls.
  • Display controls to resume a paused game.
  • Start or resume any dispatch queues that you use to execute tasks.
  • Update data source objects.
  • Start timers for periodic tasks.

We can put our configuration code in one of the following methods:

  • For a scene-based UI—The sceneDidBecomeActive(_:) method of the scene delegate object.
  • For all other apps—The applicationDidBecomeActive(_:) method of our app delegate object.

Activation is also the time to put finishing touches on our UI before displaying it to the user. Don’t run any code that might block our activation method. Instead, make sure we have everything, we need in advance. For example, if our data changes frequently outside of the app, we use background tasks to fetch updates from the network before our app returns to the foreground. Otherwise, be prepared to display existing data while we fetch changes asynchronously.


Start UI-Specific Tasks when View Appears

When our activation method returns, UIKit shows any windows that we made visible. It also notifies any relevant view controllers that their views are about to appear. We use our view controller’s viewWillAppear(_:) method to perform any final updates to our interface. For example:

  • Start user interface animations, as appropriate.
  • Begin playing media files, if auto-play is enabled.
  • Begin displaying graphics for games and immersive content at their full frame rates.

Don’t show a different view controller or make major changes to our user interface. By the time our view controller appears on-screen, our interface should be ready to display.


Conclusion

In this note series, we understood how to prepare UI to run in the foreground in iOS. We also discussed how to configure our app to appear on-screen.

Thanks for reading! I hope you enjoyed and learned about UI Preparation concepts during foreground in iOS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the 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 other website and tutorials of iOS as below links :

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

Thanks again Reading. HAPPY READING !!???

iOS – How To Manage App’s Life Cycle In iOS ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Manage App’s Life Cycle In iOS ?).

In this article, We will understand how to manage App’s Life Cycle in iOS. We will discuss how to respond to system notifications when our app is in the foreground or background, and handle other significant system-related events.

For Understanding the App’s Lifecycle concepts, We will discuss on the below topics:

  • Overview
  • Respond to The Scene-Based Life-Cycle Events
  • Responds to App-Based Life-Cycle Events
  • Respond to Other Significant Events

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.


Overview

The current state of our app determines what it can and cannot do at any time. For example, a foreground app has the user’s attention, so it has priority over system resources, including the CPU. By contrast, a background app must do as little work as possible, and preferably nothing, because it is offscreen. As our app changes from state to state, we must adjust its behavior accordingly.

When our app’s state changes, UIKit notifies us by calling methods of the appropriate delegate object:

  • In iOS 13 and later, use UISceneDelegate objects to respond to life-cycle events in a scene-based app.
  • In iOS 12 and earlier, use the UIApplicationDelegate object to respond to life-cycle events.

If we enable scene support in our app, iOS always uses our scene delegates in iOS 13 and later. In iOS 12 and earlier, the system uses our app delegate.


Respond to The Scene-Based Life-Cycle Events

If our app supports scenes, UIKit delivers separate life-cycle events for each. A scene represents one instance of our app’s UI running on a device. The user can create multiple scenes for each app, and show and hide them separately. Because each scene has its own life cycle, each can be in a different state of execution. For example, one scene might be in the foreground while others are in the background or are suspended.

Scene support is an opt-in feature. To enable basic support, add the UIApplicationSceneManifest key to our app’s Info.plist file.

The following figure shows the state transitions for scenes. When the user or system requests a new scene for our app, UIKit creates it and puts it in the unattached state. User-requested scenes move quickly to the foreground, where they appear onscreen. A system-requested scene typically moves to the background so that it can process an event. For example, the system might launch the scene in the background to process a location event. When the user dismisses our app’s UI, UIKit moves the associated scene to the background state and eventually to the suspended state. UIKit can disconnect a background or suspended scene at any time to reclaim its resources, returning that scene to the unattached state.

We use scene transitions to perform the following tasks:

  • When UIKit connects a scene to our app, configure our scene’s initial UI and load the data our scene needs.
  • When transitioning to the foreground-active state, configure our UI and prepare to interact with the user.
  • Upon leaving the foreground-active state, save data and quiet our app’s behavior.
  • Upon entering the background state, finish crucial tasks, free up as much memory as possible, and prepare for our app snapshot.
  • At scene disconnection, clean up any shared resources associated with the scene.
  • In addition to scene-related events, we must also respond to the launch of our app using our UIApplicationDelegate object.


Responds to App-Based Life-Cycle Events

In iOS 12 and earlier, and in apps that don’t support scenes, UIKit delivers all life-cycle events to the UIApplicationDelegate object. The app delegate manages all of your app’s windows, including those displayed on separate screens. As a result, app state transitions affect our app’s entire UI, including content on external displays.

App State Transitions

The following figure shows the state transitions involving the app delegate object. After launch, the system puts the app in the inactive or background state, depending on whether the UI is about to appear onscreen. When launching to the foreground, the system transitions the app to the active state automatically. After that, the state fluctuates between active and background until the app terminates.

We use app transitions to perform the following tasks:

  • At launch, initialize our app’s data structures and UI.
  • At activation, finish configuring our UI and prepare to interact with the user.
  • Upon deactivation, save data and quiet our app’s behavior.
  • Upon entering the background state, finish crucial tasks, free up as much memory as possible, and prepare for our app snapshot.
  • At termination, stop all work immediately and release any shared resources.


Respond to Other Significant Events

In addition to handling life-cycle events, apps must also be prepared to handle the events listed in the following below points. We can use our UIApplicationDelegate object to handle most of these events. In some cases, we may also be able to handle them using notifications, allowing us to respond from other parts of our app.

  • Memory warnings – Received when our app’s memory usage is too high. Reduce the amount of memory our app uses.
  • Protected data becomes available/unavailable – Received when the user locks or unlocks their device. We use applicationProtectedDataDidBecomeAvailable(_:) and applicationProtectedDataWillBecomeUnavailable(_:) methods to check protected data availability.
  • Handoff tasks – Received when an NSUserActivity object needs to be processed. We can use application(_:didUpdate:) method to handoff tasks.
  • Time changes – Received for several different time changes, such as when the phone carrier sends a time update. We can use applicationSignificantTimeChange(_:) method to see time changes.
  • Open URLs – Received when your app needs to open a resource. We can use application(_:open:options:) method to open URLs.

That’s all about in this article.


Conclusion

In this article, We understood how to manage App’s Life Cycle in iOS. We also discussed how to respond to system notifications when our app is in the foreground or background, and handle other significant system-related events in iOS.

Thanks for reading ! I hope you enjoyed and learned about App’s Lifecycle Management Concepts in iOS. 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 other website and tutorials of iOS 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 !!???

Exit mobile version