Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Navigate Between Screens In React Native ?).
In this article, We will learn how to navigate between screens in react native. Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator. This article covers the various navigation components available in React Native. If we are getting started with navigation, we will probably want to use React Navigation. React Navigation provides a straightforward navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both Android and iOS.
If we’d like to achieve a native look and feel on both Android and iOS, or we’re integrating React Native into an app that already manages navigation natively, the following library provides native navigation on both platforms: react-native-navigation.
A famous quote about learning is :
” Study hard what interests you the most in the most undisciplined, irreverent and original manner possible. “
So Let’s begin.
Overview
The community solution to navigation is a standalone library that allows developers to set up the screens of an app with a few lines of code.
React Navigation is the most popular navigation library. It handles most of the challenges described above nicely, and is sufficiently configurable for most apps.
React Navigation provides all the different type of navigator like
Stack Navigator : For the simple screen switching
Drawer Navigator : To create Navigation Drawer/ Sidebar
Bottom Tab Navigator : For the bottom navigation
Top Tab Navigator : To create the tab navigation
Navigation Challenges
There are a few aspects of navigation which make it challenging in React Native:
Navigation works differently on each native platform. iOS uses view controllers, while android uses activities. These platform-specific APIs work differently technically and appear differently to the user. React Native navigation libraries try to support the look-and-feel of each platform, while still providing a single consistent JavaScript API.
Native navigation APIs don’t correspond with “views”. React Native components like View, Text, and Image, roughly map to an underlying native “view”, but there isn’t really an equivalent for some of the navigation APIs. There isn’t always a clear way to expose these APIs to JavaScript.
Navigation on mobile is stateful. On the web, navigation is typically stateless, where a url (i.e. route) takes a user to a single screen/page. On mobile, the history of the user’s navigation state is persisted in the application so that the user can go back to previous screens – a stack of screens can even include the same screen multiple times.
Due to these challenges, there isn’t a single best way to implement navigation, so it was removed from the core React Native package.
Next, we install the required peer dependencies. We need to run different commands depending on whether our project is an Expo managed project or a bare React Native project.
If we have an Expo managed project, install the dependencies with expo:
For iOS with bare React Native project, make sure we have Cocoapods installed. Then we install the pods to complete the installation:
cd ios
pod install
cd ..
We might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. We can safely ignore most warnings as long as our app builds.
To finalize installation of react-native-gesture-handler, add the following at the top (make sure it’s at the top and there’s nothing else before it) of our entry file, such as index.js or App.js:
import 'react-native-gesture-handler';
Now, we need to wrap the whole app in NavigationContainer. Usually we’d do this in our entry file, such as index.js or App.js :
import 'react-native-gesture-handler';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
const App = () => {
return (
<NavigationContainer>
{/* Rest of app code */}
</NavigationContainer>
);
};
export default App;
Now we are ready to build and run our app on the device/simulator.
Steps For Adding React Navigation To The App
In this section, we’ll walk through adding react-navigation to an app.
After install the required dependencies, we need to do 3 things:
Set up a <NavigationContainer> from @react-navigation/native
Create a navigator:
createStackNavigator from @react-navigation/stack
createBottomTabNavigator from @react-navigation/bottom-tabs
createDrawerNavigator from @react-navigation/drawer
Define the screens in our app
1. Create a navigator
We first choose one of the available navigators, e.g. stack, which will act as our root navigator. Navigators may be nested later.
import { createStackNavigator } from '@react-navigation/stack'
const Root = createStackNavigator()
2. Create screen components
Next, we create a component for each screen.
Screens are regular React components. They’ll be passed navigation-specific props when instantiated.
Lastly, we render a NavigationContainer with our navigator within it.
Each Screen component defines a route in our app. If we want nested navigators, e.g. a tab navigator within a stack navigator, we can use another navigator as a screen’s component. We only need a single NavigationContainer, even if we have nested navigators.
For components which aren’t screens (direct descendants of a navigator), we can access the navigation and route objects using hooks. Some developers prefer using these hooks instead of props, even in screen components.
In this example, there are 2 screens (Home and Profile) defined using the Stack.Screen component. Similarly, we can define as many screens as we like.
We can set options such as the screen title for each screen in the options prop of Stack.Screen.
Each screen takes a component prop that is a React component. Those components receive a prop called navigation which has various methods to link to other screens. For example, we can use navigation.navigate to go to the Profile screen:
The views in the stack navigator use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be customized.
React Navigation also has packages for different kind of navigators such as tabs and drawer. We can use them to implement various patterns in our app.
That’s all about in this article.
Conclusion
In this article, We understood how to navigate between screens in react native. We also discussed about navigation challenges, dependencies and navigation usage in React Native platform.
Thanks for reading ! I hope you enjoyed and learned about the Navigation 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Respond To The Application Launch In iOS ?).
In this article, We will learn how to respond to the application launch in iOS. We will discuss about initialize our app’s data structures, prepare our app to run, and respond to any launch-time requests from the system in iOS. We also describe why the app launched in iOS.
A famous quote about learning is :
” Research shows that you begin learning in the womb and go right on learning until the moment you pass on. Your brain has a capacity for learning that is virtually limitless, which makes every human a potential genius. “
So Let’s begin.
Overview
The system launches our app when the user taps our app’s icon on the Home screen. If our app requested specific events, the system might also launch our app in the background to handle those events. For a scene-based app, the system similarly launches the app when one of our scenes needs to appear onscreen or do some work.
All apps have an associated process, which the UIApplication object represents. Apps also have anapp delegate object—an object that conforms to the UIApplicationDelegate protocol—which responds to important events happening within that process. Even a scene-based app uses an app delegate to manage fundamental events like launch and termination. At launch time, UIKit automatically creates the UIApplication object and our app delegate. It then starts our app’s main event loop.
Provide a Launch Storyboard
When the user first launches the app on a device, the system displays the launch storyboard until the app is ready to display its UI. Displaying the launch storyboard assures the user that our app launched and is doing something. If our app initializes itself and readies its UI quickly, the user may see the launch storyboard only briefly.
Xcode projects automatically include a default launch storyboard for us to customize, and we can add more launch storyboards as necessary. To add new launch storyboards to our project, do the following:
Open your project in Xcode.
Choose File > New > File.
Add a Launch Screen resource to our project.
Add views to our launch storyboard and use Auto Layout constraints to size and position them so that they adapt to the underlying environment. UIKit displays exactly what we provide, using our constraints to fit our views into the available space. We can use Human Interface Guidelines for for design guidance.
In iOS 13 and later, always provide a launch storyboard for your app. Don’t use static launch images.
Initialize App’s Data Structures
We put our app’s launch-time initialization code in one or both of the following methods:
application(_:willFinishLaunchingWithOptions:)
application(_:didFinishLaunchingWithOptions:)
UIKit calls these methods at the beginning of our app’s launch cycle. We use them to:
Initialize our app’s data structures.
Verify that our app has the resources it needs to run.
Perform any one-time setup when our app launches for the first time. For example, install templates or user-modifiable files in a writable directory.
Connect to any critical services that our app uses. For example, connect to the Apple Push Notification service if our app supports remote notifications.
Check the launch options dictionary for information about why our app launched.
For apps that aren’t scene-based, UIKit loads our default user interface automatically at launch time. Use the application(_:didFinishLaunchingWithOptions:) method to make additional changes to that interface before it appears onscreen. For example, we might install a different view controller to reflect what the user was doing the last time they used the app.
Move Long-Running Tasks off the Main Thread
When the user launches the app, make a good impression by launching quickly. UIKit doesn’t present the app’s interface until after the application(_:didFinishLaunchingWithOptions:) method returns. Performing long-running tasks in that method or the application(_:willFinishLaunchingWithOptions:) method might make the app appear sluggish to the user. Returning quickly is also important when launching to the background because the system limits the app’s background execution time.
Move tasks that are not critical to the app’s initialization out of the launch-time sequence. For example:
Defer the initialization of features that the app doesn’t need immediately.
Move important, long-running tasks off the app’s main thread. For example, run them asynchronously on a global dispatch queue.
Determine Why App Launched
When UIKit launches the app, it passes along a launch options dictionary to the application(_:willFinishLaunchingWithOptions:) and application(_:didFinishLaunchingWithOptions:) methods with information about why the app launched. The keys in that dictionary indicate important tasks to perform immediately. For example, they might reflect actions that the user started elsewhere and wants to continue in the app. Always check the contents of the launch options dictionary for keys that we expect, and respond appropriately to their presence.
For a scene-based app, examine the options that UIKit passes to the application(_:configurationForConnecting:options:) method to determine why it created the scene.
The example shows the app delegate method for an app that handles background location updates. When the location key is present, the app starts location updates immediately instead of deferring them until later. Starting location updates allows the Core Location framework to deliver the new location event.
class AppDelegate: UIResponder, UIApplicationDelegate,
CLLocationManagerDelegate {
let locationManager = CLLocationManager()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// If launched because of new location data,
// start the visits service right away.
if let keys = launchOptions?.keys {
if keys.contains(.location) {
locationManager.delegate = self
locationManager.startMonitoringVisits()
}
}
return true
}
// other methods…
}
The system doesn’t include a key unless our app supports the corresponding feature. For example, the system doesn’t include the remoteNotification key for an app that doesn’t support remote notifications.
That’s all about in this article.
Conclusion
In this article, We understood how to respond to the application launch in iOS. This article described about initialize our app’s data structures, prepare our app to run, and respond to any launch-time requests from the system in iOS.
Thanks for reading ! I hope you enjoyed and learned about the Application Launch 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 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Implement Animations Using The Animated API In React Native ?).
In this article, We will learn how to implement animations using the animated api in react native platform. Animation is an important part of user experience design. It serves as feedback on user actions, informs users of system status, and guides them on how to interact with the interface. This article demonstrates the practical implementation of Animations in React native application. The recommended way to animate in React Native for most cases is by using the Animated API.
A famous quote about learning is :
” He who laughs most, learns best. “
So Let’s begin.
Animation Methods
There are three main Animated methods that we can use to create animations:
Animated.timing() — Maps time range to easing value.
Animated.decay() — starts with an initial velocity and gradually slows to a stop.
Animated.spring() — Simple single-spring physics model (Based on Rebound and Origami). Tracks velocity state to create fluid motions as the toValue updates, and can be chained together.
Along with these three Animated methods, there are three ways to call these animations along with calling them individually. We will be covering all three of these as well:
Animated.parallel() — Starts an array of animations all at the same time.
Animated.sequence() — Starts an array of animations in order, waiting for each to complete before starting the next. If the current running animation is stopped, no following animations will be started.
Animated.stagger() — Array of animations may run in parallel (overlap), but are started in sequence with successive delays. Very similar to Animated.parallel() but allows us to add delays to the animations.
1. Animated.timing()
1.1 Animated.timing Basic Example
The first animation we will be creating is this spinning animation using Animated.timing().
// Example implementation:
Animated.timing(
someValue,
{
toValue: number,
duration: number,
easing: easingFunction,
delay: number
}
)
This type of infinite animation can be useful to use when creating loading indicators, and is one of the more useful animations that we’ve used in many of React Native projects. This concept can also be used to create infinite animations of other types such as scaling up and down or some other type to indicate loading.
To get started, we need to either start with a new React Native project or with a blank existing React Native project. To get started with a new project, type react-native init and the name of the project in the folder in which we will be working in and then cd into that directory:
react-native init animations
cd animations
Now that we are in this folder, open the index.js file. Now that we have a new project created, the first thing we will need to do is import Animated, Image, and Easing from react-native below View that is already being imported:
Animated is the library we will be using to create the animations, and ships with React Native.
Image is needed so we can create an image in our UI.
Easing is a module that also ships with React Native. It allows us to use various predefined easing methods such as linear, ease, quad, cubic, sin, elastic, bounce, back, bezier, in, out, inout, and others. We will be using linear as to have a consistent linear motion. We will have a better idea of how to implement them after this section is finished.
Next, we need to set an initial animated value for our spinning value. To do this, we will set the value in our constructor:
constructor () {
super()
this.spinValue = new Animated.Value(0)
}
We declare spinValue as a new Animated.Value and pass in 0 (zero). Next, we need to create a spin method and call this method on componentDidMount to get it going when the app loads:
Here, this spin() method does the following steps:
Sets this.spinValue back to zero
Calls the Animated.timing method and animates this.spinValue to a value of 1 with a duration of 4000 milliseconds and an easing of Easing.linear. Animated.timing takes two arguments, a value (this.spinValue) and a config object. This config object can take a toValue, a duration, an easing method, and a delay.
We call start() on this Animated.timing method, and pass in a callback of this.spin which will be called when the animation is completed, basically creating an infinite animation. start() takes a completion callback that will be called when the animation is done. If the animation is done because it finished running normally, the completion callback will be invoked with {finished: true}, but if the animation is done because stop was called on it before it could finish (e.g. because it was interrupted by a gesture or another animation), then it will receive {finished: false}.
Now that our methods are set up, we need to render the animation in our UI. To do so, we need to update our render method:
Here, the render() method does the following steps:
We create a variable named spin. In this variable we call interpolate()on this.spinValue. interpolate() is a method that is available to be called on any Animated.Value. interpolate is a method that interpolates the value before updating the property, e.g. mapping 0–1 to 0–10. So in our example, we need to map 0 (zero) degrees to 360 degrees numerically, using the numbers zero to one, and this method easily allows us to do this. We pass in an inputRange and outputRange array, and pass in [0,1] as the inputRange and [‘0deg’, ‘360deg’] as the outputRange.
We return a View with a style of container, and an Animated.Image (React logo) with a height, width, and a transform property in which we attach our spin value to the rotate property, which is where the animation takes place:
transform: [{rotate: spin}]
Finally, we have the container style to center everything:
Note that – Use own image url for example code testing.
The output of the above example is :
1.2 Animated.timing multiple animation Example
Now that we know the basics of Animated.timing, let’s take a look at a few more examples of how to use Animated.timing along with interpolate and declare some other animations.
In the next example, we will declare a single animation value, this.animatedValue, and use the single animated value along with interpolate to create multiple animations, animating the following style properties:
marginLeft
opacity
fontSize
rotateX
To get started, either begin with a new branch or clear out our old code from the last project.
The first thing we will do is create the animated value that we will be using for these animations in the constructor:
constructor () {
super()
this.animatedValue = new Animated.Value(0)
}
Next, we create the animate method and call it in componentDidMount() :
interpolate is a very powerful method, allowing us to use this.animatedValue , a single animated value, in many ways. Because the value simply changes from zero to one, we are able to interpolate this property for styling opacity, margins, text sizes, and rotation properties.
We then return Animated.View and Animated.Text components implementing these new variables:
Decay used to animate the value from its initial velocity down to zero using the deceleration option.
state = {
animation: new Animated.Value(-150)
}
componentDidMount() {
Animated.decay(
this.state.animation,
{
toValue: 200,
duration: 2000,
velocity: 0.95,
deceleration: 0.998 // By default equals to 0.997
}
).start();
}
To demonstrate that we are going to use Motion example. In this example, we are moving the box down the screen. Once the box reaches the finishing line at 200 points below the center, the decay effect applies. The box keeps moving, but its speed is slowing down until it stops.
The final code for this animation with a working example is :
Next, we will be creating an animation using the Animated.spring() method.
// Example implementation:
Animated.spring(
someValue,
{
toValue: number,
friction: number
}
)
We can keep going from the same project, we just need to update a few things. In our constructor, let’s create a value called springValue and set it’s value to .3:
constructor () {
super()
this.springValue = new Animated.Value(0.3)
}
Next, let’s delete the animate() method and componentDidMount() method and create a new method called spring():
Here, this spring() method does the following steps:
We set the springValue to .3 if it’s not already set to .3
We call Animated.spring, passing in two arguments: a value to animate and a config object. The config object can take any of the following arguments: toValue (number), overshootClamping (boolean), restDisplacementThreshold (number), restSpeedThreshold (number), velocity (number), bounciness (number), speed (number), tension (number), and friction (number). The only required value is toValue, but friction and tension can help us get more control over the spring animation.
We call start() to start the animation.
Now that the animation is set up, let’s attach the animation to a click event in our view, and the animation itself to the same React logo we used before:
In the animate method, we set the values of all three animated values back to zero. We then create a function called createAnimation() which returns a new animation , taking in the value, duration, easing, and delay as arguments. If no delay is passed in, we set it to zero.
We then call Animated.parallel() passing in the three animations we want to create using createAnimation().
In our render method, we next need to set up our interpolated values:
Let’s take a look at the api and see how this animation works:
// API
Animated.sequence(arrayOfAnimations)
// In use
Animated.sequence([
Animated.timing(
animatedValue,
{
//config options
}
),
Animated.spring(
animatedValue2,
{
//config options
}
)
])
Like Animated.parallel(), Animated.sequence() takes an array of animations. Animated.sequence() runs an array of animations in order, waiting for each to complete before starting the next.
Because the apis for Animated.sequence() and Animated.parallel() are so similar, taking an array of animations, we are not going to repeat the walkthrough of each method.
The main thing to notice here that is different is that we are creating our Animated.Values with a loop since we are animating so many values. We are also rendering our Animated.Views with a map function returning a new Animated.View for each item in the array.
The sequence of animations should be working now! The output of the above example is :
6. Animated.stagger()
Let’s take a look at the api and see how this animation works:
Like Animated.parallel() and Animated.sequence(), Animated.Stagger also takes an array of animations, but these animations are started in sequence with successive delays.
The main difference here is the first argument, the delay that will be applied to each animation.
The staggered animations should be working now! The output of above example is :
That’s all about in this article.
Conclusion
In this article, We understood about Animation Animation Animated API in React Native. Animation is an important part of user experience design. It serves as feedback on user actions, informs users of system status, and guides them on how to interact with the interface. We discussed how to implement Animations using Animated Api in React native with some example.
Thanks for reading ! I hope you enjoyed and learned about the Animation Animated API 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in this article (Understanding Animations In React Native).
In this article, We will learn about Animations in React Native. Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow us to convey physically believable motion in our interface.
A famous quote about learning is :
” Develop a passion for learning. If you do, you will never cease to grow.”
So Let’s begin.
Animation Systems
React Native provides two complementary animation systems:
Animatedfor granular and interactive control of specific values. It is a built-in API for animating component styles.
LayoutAnimation for animated global layout transactions. It is a built-in API for animating between 2 component hierarchies (think “magic move”), although still considered experimental.
Most animations will use Animated.
1. Animated
The Animated API is designed to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and start/stop methods to control time-based animation execution.
Animated exports six animatable component types: View, Text, Image, ScrollView, FlatList and SectionList, but we can also create own using Animated.createAnimatedComponent().
The Animated API lets us animate component styles.
For example, a container view that fades in when it is mounted may look like this:
import React, { useRef, useEffect } from 'react';
import { Animated, Text, View } from 'react-native';
const FadeInView = (props) => {
const fadeAnim = useRef(new Animated.Value(0)).current // Initial value for opacity: 0
React.useEffect(() => {
Animated.timing(
fadeAnim,
{
toValue: 1,
duration: 10000,
}
).start();
}, [fadeAnim])
return (
<Animated.View // Special animatable View
style={{
...props.style,
opacity: fadeAnim, // Bind opacity to animated value
}}
>
{props.children}
</Animated.View>
);
}
// You can then use your `FadeInView` in place of a `View` in your components:
export default () => {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<FadeInView style={{width: 250, height: 50, backgroundColor: 'powderblue'}}>
<Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text>
</FadeInView>
</View>
)
}
Let’s break down what’s happening here. In the FadeInView constructor, a new Animated.Value called fadeAnim is initialized as part of state. The opacity property on the View is mapped to this animated value. Behind the scenes, the numeric value is extracted and used to set opacity.
When the component mounts, the opacity is set to 0. Then, an easing animation is started on the fadeAnim animated value, which will update all of its dependent mappings (in this case, only the opacity) on each frame as the value animates to the final value of 1.
This is done in an optimized way that is faster than calling setState and re-rendering. Because the entire configuration is declarative, we will be able to implement further optimizations that serialize the configuration and runs the animation on a high-priority thread.
Configuring animations
Animations are heavily configurable. Custom and predefined easing functions, delays, durations, decay factors, spring constants, and more can all be tweaked depending on the type of animation.
Animated provides several animation types, the most commonly used one being Animated.timing(). It supports animating a value over time using one of various predefined easing functions, or we can use own. Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.
By default, timing will use an easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop. We can specify a different easing function by passing an easing parameter. Custom duration or even a delay before the animation starts is also supported.
For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:
Animations can be combined and played in sequence or in parallel. Sequential animations can play immediately after the previous animation has finished, or they can start after a specified delay. The Animated API provides several methods, such as sequence() and delay(), each of which take an array of animations to execute and automatically calls start()/stop() as needed.
For example, the following animation coasts to a stop, then it springs back while twirling in parallel:
Animated.sequence([
// decay, then spring to start and twirl
Animated.decay(position, {
// coast to a stop
velocity: { x: gestureState.vx, y: gestureState.vy }, // velocity from gesture release
deceleration: 0.997
}),
Animated.parallel([
// after decay, in parallel:
Animated.spring(position, {
toValue: { x: 0, y: 0 } // return to start
}),
Animated.timing(twirl, {
// and twirl
toValue: 360
})
])
]).start(); // start the sequence group
If one animation is stopped or interrupted, then all other animations in the group are also stopped. Animated.parallel has a stopTogether option that can be set to false to disable this.
Combining animated values
We can combine two animated values via addition, multiplication, division, or modulo to make a new animated value.
There are some cases where an animated value needs to invert another animated value for calculation. An example is inverting a scale (2x –> 0.5x):
const a = new Animated.Value(1);
const b = Animated.divide(1, a);
Animated.spring(a, {
toValue: 2
}).start();
Interpolation
Each property can be run through an interpolation first. An interpolation maps input ranges to output ranges, typically using a linear interpolation but also supports easing functions. By default, it will extrapolate the curve beyond the ranges given, but we can also have it clamp the output value.
A basic mapping to convert a 0-1 range to a 0-100 range would be:
For example, we may want to think about our Animated.Value as going from 0 to 1, but animate the position from 150px to 0px and the opacity from 0 to 1. This can be done by modifying style from the example above like so:
interpolate()supports multiple range segments as well, which is handy for defining dead zones and other handy tricks. For example, to get a negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, we could do:
interpolate() also supports mapping to strings, allowing us to animate colors as well as values with units. For example, if we wanted to animate a rotation we could do:
interpolate() also supports arbitrary easing functions, many of which are already implemented in the Easing module. interpolate() also has configurable behavior for extrapolating the outputRange. We can set the extrapolation by setting the extrapolate, extrapolateLeft, or extrapolateRight options. The default value is extend but we can use clamp to prevent the output value from exceeding outputRange.
Tracking dynamic values
Animated values can also track other values by setting the toValue of an animation to another animated value instead of a plain number. For example, a “Chat Heads” animation like the one used by Messenger on Android could be implemented with a spring() pinned on another animated value, or with timing() and a duration of 0 for rigid tracking. They can also be composed with interpolations:
The leader and follower animated values would be implemented using Animated.ValueXY(). ValueXY is a handy way to deal with 2D interactions, such as panning or dragging. It is a basic wrapper that contains two Animated.Value instances and some helper functions that call through to them, making ValueXY a drop-in replacement for Value in many cases. It allows us to track both x and y values in the example above.
Tracking gestures
Gestures, like panning or scrolling, and other events can map directly to animated values using Animated.event. This is done with a structured map syntax so that values can be extracted from complex event objects. The first level is an array to allow mapping across multiple args, and that array contains nested objects.
For example, when working with horizontal scrolling gestures, we would do the following in order to map event.nativeEvent.contentOffset.x to scrollX (an Animated.Value):
The following example implements a horizontal scrolling carousel where the scroll position indicators are animated using the Animated.event used in the ScrollView.
When using PanResponder, we could use the following code to extract the x and y positions from gestureState.dx and gestureState.dy. We use a null in the first position of the array, as we are only interested in the second argument passed to the PanResponder handler, which is the gestureState.
onPanResponderMove={Animated.event(
[null, // ignore the native event
// extract dx and dy from gestureState
// like 'pan.x = gestureState.dx, pan.y = gestureState.dy'
{dx: pan.x, dy: pan.y}
])}
Responding to the current animation value
We may notice that there is no clear way to read the current value while animating. This is because the value may only be known in the native runtime due to optimizations. If we need to run JavaScript in response to the current value, there are two approaches:
spring.stopAnimation(callback) will stop the animation and invoke callback with the final value. This is useful when making gesture transitions.
spring.addListener(callback) will invoke callback asynchronously while the animation is running, providing a recent value. This is useful for triggering state changes, for example snapping a bobble to a new option as the user drags it closer, because these larger state changes are less sensitive to a few frames of lag compared to continuous gestures like panning which need to run at 60 fps.
Animated is designed to be fully serializable so that animations can be run in a high performance way, independent of the normal JavaScript event loop. This does influence the API, so keep that in mind when it seems a little trickier to do something compared to a fully synchronous system. We need to check out Animated.Value.addListener as a way to work around some of these limitations, but use it sparingly since it might have performance implications in the future.
Using the native driver
The Animated API is designed to be serializable. By using the native driver, we send everything about the animation to native before starting the animation, allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. Once the animation has started, the JS thread can be blocked without affecting the animation.
Using the native driver for normal animations is straightforward. We can add useNativeDriver: true to the animation config when starting it.
Animated values are only compatible with one driver so if we use native driver when starting an animation on a value, make sure every animation on that value also uses the native driver.
The native driver also works with Animated.event. This is especially useful for animations that follow the scroll position as without the native driver, the animation will always run a frame behind the gesture due to the async nature of React Native.
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper
scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: { y: this.state.animatedValue }
}
}
],
{ useNativeDriver: true } // <-- Add this
)}>
{content}
</Animated.ScrollView>
Not everything we can do with Animated is currently supported by the native driver. The main limitation is that we can only animate non- layout properties: things like transform and opacitywill work, but Flexbox and position properties will not. When using Animated.event, it will only work with direct events and not bubbling events. This means it does not work with PanResponder but does work with things like ScrollView#onScroll.
When an animation is running, it can prevent VirtualizedList components from rendering more rows. If we need to run a long or looping animation while the user is scrolling through a list, we can use isInteraction: false in our animation’s config to prevent this issue.
2. LayoutAnimation API
LayoutAnimation allows us to globally configure create and update animations that will be used for all views in the next render/layout cycle. This is useful for doing Flexbox layout updates without bothering to measure or calculate specific properties in order to animate them directly, and is especially useful when layout changes may affect ancestors, for example a “see more” expansion that also increases the size of the parent and pushes down the row below which would otherwise require explicit coordination between the components in order to animate them all in sync.
Note that although LayoutAnimation is very powerful and can be quite useful, it provides much less control than Animated and other animation libraries, so we may need to use another approach if we can’t get LayoutAnimation to do what you want.
Note that in order to get this to work on Android, we need to set the following flags via UIManager:
In this article, We understood about Animations in React Native. Animation is an important part of user experience design. It serves as feedback on user actions, informs users of system status, and guides them on how to interact with the interface.
Thanks for reading ! I hope you enjoyed and learned about the Animations 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in this article (React Native – How To Use Touchable Components In React Native?).
In this article, we will understand about how to use Touchable Components in React Native. Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map. React Native provides components to handle all sorts of common gestures, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition, but the one component we will most likely be interested in is the basic Button. This article demonstrates the kinds of touchable with examples in React Native.
A famous quote about learning is :
” Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young. “
So Let’s begin.
Displaying a basic button
Button provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:
<Button
onPress={() => {
alert('You tapped the button!');
}}
title="Press Me"
/>
This will render a blue label on iOS, and a blue rounded rectangle with light text on Android. Pressing the button will call the “onPress” function, which in this case displays an alert popup. If we like, we can specify a “color” prop to change the color of our button.
We can see the Button component using the example below. We can select which platform our app is previewed in by clicking on the toggle in the bottom right, then click on “Tap to Play” to preview the app.
In React Native, most “buttons” are actually implemented using Touchable components. Like Button, these components support an onPress prop. However, unlike Button, these components support custom styling – essentially a Touchable is a View that can be pressed.
Touchables have a variety of other props, like onPressIn and onPressOut, which give us more control over the behavior of the button. We can use these props to run custom animations.
Kinds of Touchable
Although we can run custom animations, most of the time, we use one of 2 built-in animations: a fade in opacity, or a change of color. There are preconfigured touchable components for each of these: TouchableOpacity and TouchableHighlight.
Which “Touchable” component we use will depend on what kind of feedback we want to provide:
Generally, we can use TouchableHighlight anywhere we would use a button or link on web. The view’s background will be darkened when the user presses down on the button.
We may consider using TouchableNativeFeedback on Android to display ink surface reaction ripples that respond to the user’s touch.
TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.
If we need to handle a tap gesture but we don’t want any feedback to be displayed, use TouchableWithoutFeedback.
In some cases, we may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the onLongPress props of any of the “Touchable” components.
Gestures commonly used on devices with touchable screens include swipes and pans. These allow the user to scroll through a list of items, or swipe through pages of content.
That’s all about in this article.
Conclusion
In this article, We understood about how to use Touchable Components in React Native.
Thanks for reading ! I hope you enjoyed and learned about the Touchable Components 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 :
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:
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.
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.
If the dependency array is empty or undefined, useEffect 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.
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 :
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“
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:
Operator
Syntax
Description
Logical AND (&&)
expr1 && expr2
If 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.
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.
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.
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.
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 :
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 flexDirection, alignItems, 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:
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:
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:
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.
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 :
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 :
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.
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.
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.
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.
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.
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 backgroundColor, border-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.
styled-components uses tagged template literals to style the components using backticks (`). Each styled component must have a React Native component attached to it.
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 :