React Native Intermediate Interview Questions

1. How is the entire React Native code processed to show the final output on a mobile screen

  • At the first start of the app, the main thread starts execution and starts loading JS bundles.
  • When JavaScript code has been loaded successfully, the main thread sends it to another JS thread because when JS does some heavy calculations stuff the thread for a while, the UI thread will not suffer at all times.
  • When React starts rendering, Reconciler starts “diffing”, and when it generates a new virtual DOM(layout) it sends changes to another thread(Shadow thread).
  • Shadow thread calculates layout and then sends layout parameters/objects to the main(UI) thread. ( Here you may wonder why we call it “shadow”? It’s because it generates shadow nodes )
  • Since only the main thread is able to render something on the screen, the shadow thread should send the generated layout to the main thread, and only then UI renders.

2. What is a bridge and why is it used in React Native ? Explain for both android and IOS ?

Bridge in ReactNative is a layer or simply a connection that is responsible for gluing 
together Native and JavaScript environments.

Consider Below diagram:

  • The layer which is closest to the device on which the application runs is the Native Layer.
     
  • The bridge is basically a transport layer which acts as a connection between Javascript and Native modules, it does the work of transporting asynchronous serialized batched response messages from JavaScript to Native modules.

    Now for an example, there is some state change that happens, because of which React Native will batch Update UI and send it to the Bridge. The bridge will pass this Serialized batched response to the Native layer, which will process all commands that it can distinguish from a serialized batched response and will update the User Interface accordingly.

    IOS Platform:


     Android Platform:                      

3. Name core Components in React Native and the analogy of those components when compared with the web .

The core components used in React Native are <View> , <Text> , <Image> , <ScrollView> , <TextInput>

And analogy when compared Web can be explained by below diagram:

REACT NATIVE UI COMPONENTANDROID VIEWIOS VIEWWEB ANALOGDESCRIPTION
<View><ViewGroup><UIView>A non-scrolling <div>A container that supports layout with flexbox style, some touch handling, and accessibility controls.
<Text><TextView><UITextView><p>Displays, styles, and nests strings of text and even handles touch events.
<Image><ImageView><UIImageView><img>Displays different types of images
<ScrollView><ScrollView><UIScrollView><div>A generic scrolling container that can contain multiple components and views.
<TextInput><EditText><UITextField><input type="text">Allows the user to enter text

4. What is ListView and describe its use in React Native ?

React Native ListView is a view component that contains the list of items and displays it in a vertically scrollable list.

export default class MyListComponent extends Component {  
constructor() {  
super();  
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
this.state = {  
dataSource: ds.cloneWithRows(['Android','iOS', 'Java','Php', 'Hadoop', 'Sap', 'Python','Ajax', 'C++']), 
};
}  
render() {  
return ( 
<ListView 
dataSource={this.state.dataSource}  
renderRow={  
(rowData) =>  
<Text style={{fontSize: 30}}>{rowData}</Text>} />  
); }  
}

5. How can you write different code for IOS and Android in the same code base ? Is there any module available for this ?

The platform module detects the platform in which the app is running.

import { Platform, Stylesheet } from 'react-native';
const styles = Stylesheet.create({
height: Platform.OS === 'IOS' ? 200 : 400
})

Additionally Platform.select method available that takes an object containing Platform.OS as keys and returns the value for the platform you are currently on.

import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
 container: {
flex: 1,
   ...Platform.select({
     ios: {
       backgroundColor: 'red',
     },
     android: {
       backgroundColor: 'green',
     },
     default: {
       // other platforms, web for example
       backgroundColor: 'blue',
     },    }),
},
});

6. What are Touchable components in react Native and which one to use when ?

Tapping gestures can be captured by Touchable components and can display feedback when a gesture is recognized.

Depending on what kind of feedback you want to provide we choose Touchable Components.

Generally, we use TouchableHighlight anywhere you would use a button or link on the web. The background of the view will be darkened when the user presses down on the button.

We can use 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 you don’t want any feedback to be displayed, use TouchableWithoutFeedback.

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';
export default class Touchables extends Component {
_onPressButton() {
   alert('You tapped the button!')  }
 _onLongPressButton() {
   alert('You long-pressed the button!')
 }
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._onPressButton} underlayColor="white">
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableHighlight</Text>
</View>
</TouchableHighlight>
);}
}

7. Explain FlatList components, what are its key features along with a code sample ?

The FlatList component displays similarly structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time.

Key Feature:

The FlatList shows only those rendered elements which are currently displaying on the screen, not all the elements of the list at once.

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

export default class FlatListBasics extends Component {  
 
   renderSeparator = () => {  
       return (  
           <View  
               style={{  
                   height: 1,  
                   width: "100%",  
                   backgroundColor: "#000",  
               }}  
           />  
       );  
   };  
   //handling onPress action  
   getListViewItem = (item) => {  
       Alert.alert(item.key);  
   }  
 
   render() {  
       return (  
           <View style={styles.container}>  
               <FlatList  
                   data={[  
                       {key: 'Android'},{key: 'iOS'}, {key: 'Java'},{key: 'Swift'},  
                       {key: 'Php'},{key: 'Hadoop'},{key: 'Sap'},  
                   ]}  
                   renderItem={({item}) =>  
                       <Text style={styles.item}  
                             onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}  
                   ItemSeparatorComponent={this.renderSeparator}  
               />  
           </View>  
       );  
   }  
}  
AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics);  

8. How To Use Routing with React Navigation in React Native ?

One of the popular libraries for routing and navigation in a React Native application is React Navigation.

This library helps solve the problem of navigating between multiple screens and sharing data between them.

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

const MyStack = () => {
 return (
   <NavigationContainer>
     <Stack.Navigator>
       <Stack.Screen
         name="Home"
         component={HomeScreen}
         options={{ title: 'Welcome' }}
       />
       <Stack.Screen name="Profile" component={ProfileScreen} />
     </Stack.Navigator>
   </NavigationContainer>
 );
};

9. What are the Different Ways to style React Native Application ?

React Native give us two powerful ways by default to style our application :

1 ) Style props

You can add styling to your component using style props. You simply add style props to your element and it accepts an object of properties.

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
export default class App extends Component<Props> {
render() {
return (
<View style={{flex:1,justifyContent:"center",backgroundColor:"#fff", alignItems:"center"}}>
<View style={{width:200,height:150,backgroundColor:"red",padding:10}}>
<Text style={{fontSize:20, color:"#666"}}>Styled with style props</Text>
</View>
</View>
);
}
}

 2 )  Using StyleSheet

For an extremely  large codebase or you want to set many properties to your elements, writing our styling rules directly inside style props will make our code more complex that’s why React Native give us another way that let us write a concise code using the StyleSheet method:

import { StyleSheet} from 'react-native';
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent:"center",
backgroundColor:"#fff",
alignItems:"stretch"
},
title: {
fontSize:20,
color:"#fff"
},
item1: {
backgroundColor:"orange",
flex:1
},
item2: {
backgroundColor:"purple",
flex:1
},
item3: {
backgroundColor:"yellow",
flex:1
},

});

 We then  pass the styles object to our component via the style props:

<View style={styles.container}>
<View style={styles.item1}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item2}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item3}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
<View style={styles.item4}>
<Text style={{fontSize:20, color:"#fff"}}>Item number 1</Text>
</View>
</View>

3 ) styled-components in React Native

We can also use styled-components with React native so you can write your styles in React Native as you write normal CSS. It is very easy to include it in your project and it doesn’t need any linking just run this following command inside the root directory of your app to install it:

yarn add styled-components

import React, {Component} from 'react';
import { StyleSheet,Text, View} from 'react-native';
import styled from 'styled-components'
const Container=styled.View`
   flex:1;
   padding:50px 0;
   justify-content:center;
   background-color:#f4f4f4;
   align-items:center
`
const Title=styled.Text`
font-size:20px;
text-align:center;
color:red;
`
const Item=styled.View`
flex:1;
border:1px solid #ccc;
margin:2px 0;
border-radius:10px;
box-shadow:0 0 10px #ccc;
background-color:#fff;
width:80%;
padding:10px;

`

export default class App extends Component {
 render() {
   return (
     <Container>
            <Item >
            <Title >Item number 1</Title>
            </Item>
            <Item >
            <Title >Item number 2</Title>
            </Item>
            <Item >
            <Title >Item number 3</Title>
            </Item>
            <Item >
            <Title >Item number  4</Title>
            </Item>
     </Container>
   );
 }

20. Explain Async Storage in React Native and also define when to use it and when to not?

  • Async Storage is the React Native equivalent of Local Storage from the web.
  • Async Storage is a community-maintained module for React Native that provides an asynchronous, unencrypted, key-value store. Async Storage is not shared between apps: every app has its own sandbox environment and has no access to data from other apps.
DO USE ASYNC STORAGE WHEN..DON’T USE ASYNC STORAGE FOR..
Persisting non-sensitive data across app runsToken storage
Persisting Redux stateSecrets
Persisting GraphQL state 
Storing global app-wide variables 

21. What is React Native?

React Native is an open source framework developed by Facebook which enables developers to build cross-platform mobile applications using Javascript. With React Native, one can develop a mobile application by using the same design principles used to develop a web application with ReactJs framework. It allows the developer to build mobile application UI by composing multiple components in a declarative way. Before React native, there were few options like Cordova, ionic available to build a hybrid application. 

These applications were written using web technology but the hybrid app was not a native application and lacks performance issue. React native solves those performance issues that is why it quickly became popular in React community. Under the hood, React native bridge invokes the native rendering APIs in Objective-C (for IOS) and Java (for Android). That is why they perform better than hybrid application development frameworks. React native has a very good community of developers who actively contribute to the framework. Its code is available on Github and has 70k+ stars.

22.What are the benefits of using React Native for building mobile applications?

There are following benefits of using React Native in mobile application development

  1. React Native enables a web developer to build mobile apps with Javascript.
  2. The developer doesn’t need to learn complete new programming language java/ Kotlin to develop Android App. Similarly, the developer doesn’t need to be an expert in objective C or swift to develop IOS app anymore. Javascript is more than sufficient to build a mobile app for both Android and IOS. However, knowing java or swift helps the developer to write performance robust mobile app.
  3. With React Native, most of the code base can be shared between the Android app and the IOS app.
  4. With a single code base, effort in maintenance is reduced by many folds.
  5. With a single code base, features can be shipped much faster on both major mobile platform
  6. Developer having experience with ReactJs can quickly learn React Native. The learning curve for a developer is very low.
  7. App developed with React Native is not a web app running inside a mobile app. It is a real mobile app because it uses the same fundamental building blocks as regular IOS native app and Android app uses.
  8. React Native lets you build an app faster as it’s tool gives hot reloading functionality out of the box which means we don’t need to recompile app again and again on making changes.
  9. React Native gives the flexibility to use Native swift or java module with React Native application. So your app can get the best from both worlds.

23. How is React Native different from other frameworks for developing a mobile application?

Javascript developer always tried to explore platforms where Javascript can be used to build better user experiences. React native is not the first framework which enables web developers to build applications for the mobile platform. Ionic, Cordova were few very popular application framework which was used to develop a mobile application using web technologies. One major motivation towards this effort was having a seamless experience on all the platforms. Mobile application developed with React Native is different than alternate frameworks in the following ways:

  1. React Native app is a real mobile app, not a web app running inside a mobile app shell. Other alternative like Cordova, ionic run a web app in a web view.
  2. React Native app is converted into machine code which runs on mobile that is why it gives better performance than other alternatives.
  3. React Native mobile apps are more close to Native app development in comparison to other Javascript frameworks
  4. Mobile application built with React native has small bundle size in comparison to older hybrid application development framework.

24. Name a few companies or applications that are built using React Native?

There are many renowned companies developing their mobile app with React Native. Big companies like Facebook, Airbnb, Instagram, Pinterest, Uber, Tesla are a few names whose main consumer-facing mobile app is developed with React Native. This shows their trust in the React native framework. Airbnb was a very early adopter of React native. They actively shared their experience with React native framework. 

They also open sourced many React native library built on top of React native framework. One of their famous libraries is Lottie which makes complex animations work in React native. Many startups are using React native to build their mobile app using React native. They are able to quickly launch their idea on Android and IOS platform at once. Instagram is also built with React native and able to handle large user interaction. This clearly shows that React native is very mature and robust mobile app development framework available today.

25. What tool and skill set do you need to develop a mobile app in React Native?

Developer experience is one of the most important attributes of a framework. If getting started step with any framework is very difficult and very complex then the community will take lots of time to accept that framework. That is why React native has tried their best to simplify the getting started step for app development. To build a mobile app with React Native, one should have a good understanding of Javascript concepts and understanding of CSS helps in styling React Native app. React Native provide CLI (command line interface) which is used to bootstrap the mobile application. 

For IOS development Xcode and for Android app development, Android studio is required. Understanding of component driven development with ReactJs is also very beneficial in React Native app development. There is one more open source project named Expo CLI which provides a command line utility to easily start development of React native. It also provides barcode based approach to share the app within the team. Developer experience is pretty good for React native that is also one of the reasons for its huge popularity in the developer community.

26. How mobile app development with React Native is different than web app development with ReactJS

ReactJS and React native, both are developed and open sourced by Facebook Inc. React native framework follows the React JS framework’s basic architecture. React native also promotes a component-based approach to build mobile screens. All the React natives possess similar lifecycle methods which are exposed by React js component. But still, there are a few differences between ReactJS and React Native

  1. We use div, span etc. HTML tags to build the UI of the web application but in case of React Native, we use View, Text imported from React Native library.
  2. Since React Native is used to developing for Native platform, we can’t access the browser features like window object, local storage etc…
  3. React JS and React native are two different open source project on Github.
  4. Any new feature related to component architecture first implement by ReactJS and then support is added in React Native framework.
  5. Both have different tooling for getting started with development.

27. What is JSX?

JSX is a system used for embedding XML in Javascript. You can say that JSX is a templating language for writing HTML/XML tags with Javascript. With the help of JSX, HTML/XML can be written inside Javascript file. JSX enables conditional rendering of React components. React includes building step which converts JSX into Javascript code which is ultimately executed by browser in case of a web app or react Native in case of React Native. JSX is added to improve the developer experience. ReactJS provides few APIs which make the HTML structure in a browser. Those APIs were a little cumbersome to frequently used. That is why React JS introduced JSX and added a tooling step to convert JSX into platform understandable code. With the help of JSX, we can execute javascript to build HTML tags very easily.  Here is an example of a JSX code:

<View style={styles.container}>
<TouchableOpacity onPress={this.decrement}>
<Text style={styles.text}>-</Text>
</TouchableOpacity>
<Text style={styles.text}>{this.state.count}</Text>
<TouchableOpacity onPress={this.increment}>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
</View>

Above JSX code is creating one View component which contains two TouchableOpacity component as its child element. We are accessing Javascript variable in Text component with curly brace.

28. What is component driven development and what are the benefits of using component driven development?

Long time back, web developer realises that there are few elements which are frequently used in web development like drop down and different type of button. The developer started making CSS frameworks which provide already developed components. Bootstrap was first very popular CSS framework which helped web developer to build user experience very quickly. React also follows the same approach in web development. 

Component driven development is a methodology where we break the complete UI design into several small reusable components and develop them independently. Then the complete UI is built by composing these small components. This methodology helps us write UI code in a modular way. UI development will be faster as we will be reusing components at multiple places. Less code also results in less effort in maintaining the code and also less number of bugs. So we can say that component driven development was already there in web development but React JS made it very popular in the developer community. New frameworks like Angular4+ are also following the same methodology to develop the web application.

29. What are props in React Component?

Props are parameters which are used to customise a component at the time of creation and on re-render. Props are like arguments passed to a React component. For example, Image is a very basic component provided by React Native library to display an image. It accepts a prop called source which is used to control what image it shows. By passing different values of props, one component can show different UI and different functionality. So we can say that props help use and reuse the same component at different places. Props are set by the parent component and remain fixed for an entire lifecycle of a component.

React Component
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Counter from './components/Counter';
import Greeting from "./components/Greeting2";
import SimpleTextInput from './components/SimpleTextInput';
import SimpleButton from './components/SimpleButton';
import LoginForm from './components/LoginForm';
import PictureList from './components/PictureList';

export default class App extends React.Component {
  render() {
    const pictureData = {
      uri: 'https://picsum.photos/300/300'
    };
    return (
      <View style={styles.container}>
        <PictureList />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5fcff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    margin: 5,
    borderRadius: 5,
    width: 300,
    height: 300
  }
});

30. What is state in the React component?

State is another way apart from props by which we can modify a React component. React component’s state value changes in the life cycle of component, unlike props. We should not directly change state value of react component. React framework gives the setState method by which state of a component should be changed.

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

class Counter extends React.Component {
    state = { count: 0 };
    increment = () => this.setState({count: this.state.count + 1});
    decrement = () => this.setState({count: this.state.count - 1});
    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.decrement}>
                    <Text style={styles.text}>-</Text>
                </TouchableOpacity>
                <Text style={styles.text}>{this.state.count}</Text>
                <TouchableOpacity onPress={this.increment}>
                    <Text style={styles.text}>+</Text>
                </TouchableOpacity>
            </View>
        );
    }
};
const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        borderRadius: 5,
        borderWidth: 1,
        borderColor: '#1a91b8',
        padding: 5,
        backgroundColor: '#eaf7fd'
    },
    text: {
        color: '#015169',
        fontWeight: 'bold',
        fontSize: 20,
        padding: 15
    }
});
export default Counter;

Above code is an implementation of a counter component. This component has a state count whose value is changed by clicking on the plus (+) and minus (-) button. As the state count of this component is changing the number displayed on UI is also changing. Whenever we create any component in React, first we divide the screen in the component then decide what state a component should have. The beauty of this component is that it is an independent component and can be used anywhere in the application. That is how we make several fully functional component in React to build the complete application.

31. How do you start the React Native app development?

Starting a project from scratch is always a little bit harder that is why there are some tooling available which we can use to bootstrap a React Native project.

  • Using react-native-cli (https://www.npmjs.com/package/react-native-cli)
    • react-native-cli created a pure react native application as it doesn’t hide any piece of code in the generated project. You can see ios and android folder in a directory structure. Although, you don’t need to modify anything inside generated ios and android folder, They are required to run React native application successfully on the device.
  • Using expo-cli (https://www.npmjs.com/package/expo-cli)
    • Expo-Cli is a third party tooling which provides base files and easy setup steps to start React Native app development. It also provides barcode based steps to share the app with other team members. The downside of bootstrapping React native app with expo cli is the size of the basic app is considerably big as expo cli includes few expo based libraries with the app.

32. Why do you need to install watchman software when setting up a development environment for React Native on MacOS?

Watchman is an open source project developed by Facebook. As the name of the software correctly suggests that it watches files and keep track of changes in files. It can also trigger action based on file change. React native uses watchman to provide hot reloading feature of React Native. Hot reloading of React native application helps the developer to build application faster. 

Native mobile application development doesn’t have this feature which means, a developer has to make changes and compile the project to see an out on the device. But React native saves time by automating this task and provide hot reloading. With React native, if the developer makes any change in the project file, the watchman will detect the change and invoke the build to reflect the changes automatically without any developer intervention. Hot reloading feature of React native make it a developer friendly framework and definitely speed up the development. Installation of the watchman is mentioned in the React native’s environment setup step.ac

33. How do you style your React Native component?

Every React Native component like View, Text, Image etc… accepts a style prop which is an object of CSS rules. The only difference between CSS rules and CSS object used in React Native is key in CSS object has CSS rules in camelCase, for example, CSS rule background-colour will become backgroundColour in React Native. There are few restrictions over values of some CSS rules. But still, available CSS rules are enough to style a mobile app UI beautifully. React Native supports CSS flexbox to build UI layouts. We style our mobile screen like below snippet:

const styles = StyleSheet.create({
   container: {
       flexDirection: 'row',
       borderRadius: 5,
       borderWidth: 1,
       borderColor: '#1a91b8',
       padding: 5,
       backgroundColor: '#eaf7fd'
   },
   text: {
       color: '#015169',
       fontWeight: 'bold',
       fontSize: 20,
       padding: 15
   }
});
Then we can use these style with View component like below:
<View style={styles.container}></View>

Stylesheet object is provided by React native library which has the method “create”. It takes an argument of type object and this object is the collection of CSS rules. As you can see in the above example, font-size CSS property in the web becomes font size in React native and flex-direction becomes flexDirection. I hope you got the idea about styling in React native application development. You can find the complete code on https://gist.github.com/PavanKu/98f92103af84faaf540aa348cf1a1126

34. How do you handle elements size in React Native?

React native follows the box-model concept of CSS. The size of the element is calculated based on the size of content, padding, border, margin. The simplest way to set the size of an element is to set width and height CSS property for an element. All dimensions in React Native is unitless and represent density-independent pixels. By setting fixed height and width, the element will look exactly the same size on different screen sizes. But there is an instance where you want to give the width and height of an element in percentage. 

Directly use of percentage is not supported in React native but React native does give a dimension module which can be used to give width in percentage. Dimension module gives the width and height of the mobile device. This information can be used to set the style of an element in runtime. Below is the example of how to use Dimension module from React native:

Importing module from React Native:
import { Dimension } from ‘react-native’;
Figure out width and height of the device:
const deviceWidth = Dimension.get(“window”).width;
const deviceHeight = Dimension.get(“window”).height;
Calculate the style value:
Width: deviceWidth*<percentageValue>/100

But the simplest way is by setting width and height CSS for an element.

35. How CSS flexbox is used to layout a React Native UI

By default, View component in React native has the display set to flex. Flex is a CSS property which is used to expand and shrink a component dynamically based on available space. If you set flex:1 then the component will take up all the available space. If a parent element is given flex:1 then all its child elements will evenly distribute available space among themselves. We can change the width of the child element by giving a higher value of flex property. 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 the available space if its parent has dimensions greater than 0. To make flex work, the parent element must have some width set to it then only flex property will evenly distribute available space. Otherwise, the element will consider width equal to zero and will not be visible on UI. Along with flex property, alignItems and justify-content CSS properties are also used to design mobile UI.

36. What are the differences between Flexbox in browser and Flexbox in React Native?

CSS Flexbox is used to design a responsive layout easily without using float or position CSS property. Float and position values were used to build any type of UI which are not very easy. Flexbox is added in CSS3. Flexbox is designed to provide a consistent layout on different screen sizes. You will normally use a combination of flexDirection, alignItems, and justify-content to achieve the right layout. 

There are few differences in default values of few flex based CSS properties between React Native and on the browser. The default value of flexDirection is a row in the web but in case of React native, its default value is a column. Also, flex parameter only supports a single number in React native. Flexbox alignItems has few more values like flex-start which start aligning element from start and opposite of this is flex-end which places the first child element at the end. Similar to alignItems, justifyContents also have values which behaves where much similar to flexbox behaviour in a web browser.

37. How does justifyContent flexBox property work?

JustifyContent property aligns the flexible container’s items when the items do not use all available space on the main axis. By default, the main axis is a vertical axis in case of React native. Which means justifyContent property aligns child elements of flex parent vertically in React native.  We can use this property to layout elements in a flex container. JustifyContent supports the following values: flex-start|flex-end|centre|space-between|space-around|initial|inherit; It also apply some control over the alignment of items when they overflow the line. Let me explain JustifyContent’s values:

  • flex-start: this is the default value for justifyContent. It means that flex items will start from the top and evenly distributed vertically.
  • Flex-end: this is just the opposite behaviour of flex-start. Elements start rendering from the bottom
  • Center: Items will be placed in the middle
  • Space-between: elements are evenly distributed along the main axis (vertical axis)
  • Space-around: flex items will be evenly distributed with equal space around them

38. How does alignItems flexBox property works?

You can think of alignItems as justifyContent behaviour for cross axis. Cross-axis in case if React native is the horizontal axis. CSS alignItems property sets the alignSelf value on all direct children as a group. In Flexbox, it controls the alignment of items on the cross axis. By default, the cross axis is a horizontal axis in case of React native. We can use this property to layout elements in the flex container. The alignItems property supports following values: stretch|center|flex-start|flex-end|baseline|initial|inherit;  Let me explain alignItems values:

  • flex-start: this is the default value for alignItems. It means that flex items will start from the left and evenly distributed horizontally.
  • Flex-end: this is just the opposite behaviour of flex-start. Elements start rendering from the right and go up to the left end.
  • Center: Items will be placed in the middle
  • Space-between: elements are evenly distributed along the cross axis (horizontal  axis)
  • Space-around: flex items will be evenly distributed with equal space around them

39. How can we change the default behaviour of the main axis and cross axis of flexbox layout?

By default, the main axis is the vertical axis and cross axis is the horizontal axis in React native. Since justifyContent and alignItems property works based on the main axis and cross axis, so justifyContent will align flex items vertically and alignItems will layout flex item horizontally. This default value of the main axis and cross axis can be changed by changing flexDirection property. If we set flexDirection to row in the flex container then the main axis will become horizontal axis and cross axis will become vertical axis. 

On changing default behaviour via flexDirection CSS property, the behaviour of alignItems and justifyContent will also get switched. The Concept of flexDirection is also present on the web. Flexbox is implemented as a single direction layout technique and this direction is managed by flexDirection CSS property. Apart from row and column, the flexDirection property has two more values: row-reverse and column-reverse. As the name suggests, the direction will remain horizontal and vertical but the direction will get changed.

40. What all CSS properties are not supported by React native?

Though most of the CSS properties works in the same way in React native still there are few differences in CSS property values between a browser and React native:

  1. Only two values of CSS property display (none, flex) is supported in React native. display none is used to hide an element.
  2. aspectRatio is non-CSS property supported by React Native. we can use aspect ratio to give a size to an element. if either width or height is specified along with aspect ratio then other parameters will be calculated and applied based on aspect ratio value
  3. marginHorizontal has the same effect as setting both marginLeft and marginRight. Similar to marginHorizontal, marginVertical has the same effect as setting both marginTop and marginBottom.
  4. The default value of the position in React native is relative instead of static. so absolute positioning is always just relative to the parent.

Apart from the above difference, most of the CSS properties work exactly the same as they work in a browser.

41. What are the ways to write react components?

here are two ways of writing a react component

  • Functional component
    • It uses a simple function which returns the JSX
  • Class-based component
    • It used the class keyword introduced in ES6. it implements render lifecycle method which returns the JSX.

Example of functional component

Functional component

Example of class-based component

Class-based component
/* Class based component */
import React, { Component } from 'react';
import { Text } from 'react-native';

export default class Greeting extends Component {
    render() {
        return (
            <Text>Hello {this.props.name} !</Text>
        );
    }
}

/* Functional component */
import React, { Component } from 'react';
import { Text } from 'react-native';

export default function Greeting(props) {
        return (
            <Text>Hello {props.name} !</Text>
        );
}

cases are known as a presentational or dumb component. The functional component gets information via props from its parent component and renders the information. You can see that the functional component accepts props as an argument. ES6 arrow function also is used to define a functional component. The functional component doesn’t store any state and also doesn’t override any lifecycle method of React component. The class-based component has the ability to store state within the component and based on its state value behave differently. The latest version of React 16.8 has included a new feature called React hooks by which we can add state in a functional component.

42. What is the difference between a functional component and a class-based component?

Though we can implement in both functional and class-based way, there are few fundamental differences between the two of them:

  1. Functional component can’t have stated ( before React hooks era ). It renders component only based on props passed. A class-based component can have a local state which can be helpful in building a bigger component
  2. Functional component access directly via props argument passed. In a class-based component, props are accessible via this.props.
  3. A class-based component is a more complex structure. It is an instance of a class derived from React. Component class. The class must implement a render() member function which returns a React component to be rendered
  4. The class-based component can also use lifecycle methods but functional component can’t use lifecycle methods.
  5. Functional components are a very light weighted component in comparison to class-based react component

43. Give a quick overview of the life cycle of a React component?

Below image summarise the lifecycle methods exposed by react component and the order in which lifecycle methods are being called by React.

life cycle of a React component

React 16 was a major release for ReactJS. With this version react has marked some of the lifecycle methods like componentWillRecieveProps, ComponentWillUpdate as deprecated. In a later release of React, the framework will be removing these methods. In place of deprecated methods, they added a few new lifecycle methods. The above picture shows the lifecycle method of a component. We can divide the lifecycle methods of the component into three categories.

  • Mounting: This includes the beginning phase of the component. The first constructor of the component gets invoked. Constructor receives props as an argument from the parent component. Constructor is the place where we define an initial state of a component. After constructor and before render, lifecycle method getDrivedStateFromProps is invoked, it returns the state object or null to avoid the render. Then Render method is invoked which renders the JSX. Then at the end, componentDidMount is invoked.
  • Updating: A component gets an update via a change in state or change in props. In both of these cases, the getDrivedStateFromProps method is invoked first where we get props and state as an argument and returns updated state. Then shouldComponentUpdate methods are invoked. If this method returns true then the only component gets the update otherwise component update is aborted. Then render method is called and after this getSnapshotBeforeUpdate is called. In the end, the componentDidUpdate method is called
  • Unmounting: componentWillUnmount lifecycle method is invoked before the unmounting of the component takes place.

44. How do you create basic text input to React Native?

TextInput is provided by React native framework to implement simple text input control. Text input is one of the very basic controls of UI. Whether it is auto-complete, form, text input is a must used control in UI of application. TextInput component accepts placeholder value as props. When a user starts changing the text then the onChangeText event is triggered and when the user is done editing and hit return button, onSubmitEditing props will get invoked. TextInput component can be styled by setting style props to the component. Here is an example of the implementation of simple text input in React native:

 basic text input to React Native
import React from 'react';
import { View, Text, TextInput, StyleSheet } from "react-native";

class SimpleTextInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = { text: '', isSubmitted: false };
    }
    handleChangeText = (text) => {
        this.setState({ text, isSubmitted: false });
    }
    handleSubmitText = () => {
        this.setState({ isSubmitted: true });
    }
    render() {
        const { text, isSubmitted } = this.state;
        return (
            <View style={styles.container}>
                <TextInput
                    style={styles.input}
                    placeholder={'Type here...'}
                    onChangeText={this.handleChangeText}
                    onSubmitEditing={this.handleSubmitText}/>
                <Text style={styles.text}>{isSubmitted?`User has typed: ${text}`:'User is typing'}</Text>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        margin: 10,
        padding: 10,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 5,
        backgroundColor: '#eaf7fd'
    },
    text: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#015169'
    },
    input: {
        height: 40
    }
});

export default SimpleTextInput;

In the above example: we have a TextInput component whose value is controlled by the state. Which means our TextInput in above example is a controlled component. Once the user starts typing we update the state with an onChangeText method. Once the user submits the value, we display the value user has typed in the text box.

45. How do you create a basic button in React Native?

React native provides Button component which displays platform specific button. Following example shows how we create a platform-specific default button in React native. Platform-specific button means that the look and feel on a button will depend on whether the application is running on IOS or Android. Button component exposes two main props: title and onPress. Title props are used to display text on the button. onPress props is a callback which is invoked when the user presses the button. This is very much similar to the click event on a web browser. We can’t style the Button component provided by React native.

Basic button in React Native
import React from 'react';
import { View, Alert, Button, StyleSheet } from "react-native";

const SimpleButton = (props) => {
    return ( <Button style={styles.button} onPress={() => Alert.alert("You pressed button")} title="Click Me"/> );
};

const styles = StyleSheet.create({
    button: {
        padding: 5,
        color: '#000'
    }
});

export default SimpleButton;

Above example will show platform specific alert when the user presses the button. Alert is the component provided by React native framework to show platform specific modal. As I mentioned above that we can’t style Button component of React native, we can try this by changing the text colour of a button or changing the padding via style props but it won’t change the appearance of the button.