Author: saqibkhan

  • React Native Layout and Flexbox

    React Native Flexbox is an algorithm to specify the layout of component’s children. It provides a consistent layout on different screen sizes.

    Property of Flexbox

    Flexbox provides three main properties to achieve the desired layout. These properties are: flexDirectionjustifyContent, and alignItems.

    PropertyValuesDescription
    flexDirection‘column’, ‘row’Used to align its elements vertically or horizontally.
    justifyContent‘center’, ‘flex-start’, ‘flex-end’, ‘space-around’, ‘space-between’Used to distribute the elements inside the container.
    alignItems‘center’, ‘flex-start’, ‘flex-end’, ‘stretched’Used to distribute the element inside the container along the secondary axis (opposite to flexDirection).

    React Native Flex Direction

    The flexDirection adds the style to the component in a primary axis of its layout. It has a property row and column to organize children horizontally and vertically respectively. The default flexDirection is a column.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class FlexDirectionBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘row’,// set elements horizontally, try column.  
    19.     },  
    20.     powderblue:{  
    21.         width: 60,  
    22.         height: 60,  
    23.         backgroundColor: ‘powderblue’,  
    24.     },  
    25.     skyblue:{  
    26.         width: 60,  
    27.         height: 60,  
    28.         backgroundColor: ‘skyblue’,  
    29.     },  
    30.     steelblue:{  
    31.         width: 60,  
    32.         height: 60,  
    33.         backgroundColor: ‘steelblue’,  
    34.     }  
    35. })  

    Output

    React Native Layout and Flexbox

    React Native Justify Content

    The justifyContent determines the distribution of children component along the primary axis. The children component are distributed at the start, end, center, or space evenly.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class JustifyContentBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘column’, // set elements horizontally`.  
    19.         justifyContent: ‘center’,  
    20.   
    21.     },  
    22.     powderblue:{  
    23.         width: 60,  
    24.         height: 60,  
    25.         backgroundColor: ‘powderblue’  
    26.     },  
    27.     skyblue:{  
    28.         width: 60,  
    29.         height: 60,  
    30.         backgroundColor: ‘skyblue’,  
    31.     },  
    32.     steelblue:{  
    33.         width: 60,  
    34.         height: 60,  
    35.         backgroundColor: ‘steelblue’,  
    36.     }  
    37. })  

    Output

    React Native Layout and Flexbox

    React Native Align Items

    The alignItems determine the alignment of children component along the secondary axis. If the primary axis is a column, then the secondary is a row, and when a primary axis is a row, then the secondary is a column. Using the alignItems, the children are aligned at start, end, center, or stretched.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class AlignItemsBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘column’, // set elements horizontally`.  
    19.         justifyContent: ‘center’,  
    20.         alignItems: ‘stretch’,  
    21.     },  
    22.     powderblue:{  
    23.         width: 60,  
    24.         height: 60,  
    25.         backgroundColor: ‘powderblue’  
    26.     },  
    27.     skyblue:{  
    28.         width: 60,  
    29.         height: 60,  
    30.         backgroundColor: ‘skyblue’,  
    31.     },  
    32.     steelblue:{  
    33.         /*width: 60,*/  
    34.         height: 60,  
    35.         backgroundColor: ‘steelblue’,  
    36.     }  
    37. })  

    Output

    React Native Layout and Flexbox
  • React Native Button

    Most users interact with mobile through touches. There are combinations of gestures that work on it, such as tapping on the button, zooming the map, scrolling a list, etc. A button is one of the components that work on its click.

    React Native Button is a basic component that works by clicking on it. It imports the Button class of react-native.

    Props of Button

    PropTypeRequiredDescription
    onPressfunctionyesCall the handler when user clicks the button.
    titlestringyesDisplay the text inside the button.
    accessibilityLabelstringnoDisplay the text for blindness accessibility features.
    colorColornoSet the background color of the Android button or set the color of iOS text.
    disabledboolnoIt disables all interactions for this component, if true.
    textIDstringnoUsed to locate this view in end-to-end tests.
    hasTVPreferredFocusboolnoIt preferred TV focus work only for Apple TV.

    React Native Button Example

    In this example, we will work on the button component. React Native Button component imports the Button class of react-native library. It has several props such as title, onPress, accessibilityLabel, etc. which are mentioned above.

    In the previous article Positioning Element with Flex, we learned how to position elements in View.

    In the below code the title prop sets the title of a button, onPress prop calls the mention function and performs an event. The color prop sets the color of the button, and disabled={true} makes the button to disable.

    1. import React, { Component } from ‘react’;  
    2. import { Alert, AppRegistry, Button, StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class ButtonBasics extends Component {  
    5.     onPressButton() {  
    6.         Alert.alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <View style={styles.container}>  
    12.                 <View style={styles.buttonContainer}>  
    13.                     <Button  
    14.                         onPress={this.onPressButton}  
    15.                         title=”Press Me”  
    16.                     />  
    17.                 </View>  
    18.                 <View style={styles.buttonContainer}>  
    19.                     <Button  
    20.                         onPress={this.onPressButton}  
    21.                         title=”Press Me”  
    22.                         color=”#009933″  
    23.                     />  
    24.                 </View>  
    25.                 <View style={styles.multiButtonContainer}>  
    26.                     <Button  
    27.                         onPress={this.onPressButton}  
    28.                         title=”A disabled button”  
    29.                         disabled={true}  
    30.                     />  
    31.                     <Button  
    32.                         onPress={this.onPressButton}  
    33.                         title=”OK!”  
    34.                         color=”#009933″  
    35.                     />  
    36.                 </View>  
    37.             </View>  
    38.         );  
    39.     }  
    40. }  
    41.   
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: ‘center’,  
    46.     },  
    47.     buttonContainer: {  
    48.         margin: 20  
    49.     },  
    50.     multiButtonContainer: {  
    51.         margin: 20,  
    52.         flexDirection: ‘row’,  
    53.         justifyContent: ‘space-between’  
    54.     }  
    55. })  

    Output:

    React Native Button
    React Native Button
  • React Native Height and Width

    The height and width determine the size of component on the screen. There are two different ways to set the height and width of component: Fixed Dimensions and Flex Dimensions.

    Fixed Dimensions

    Using fixed height and fixed width in style is the simplest way to set the dimension of the component. The dimensions of React Native component are unit-less, and they represent density-independent pixels.

    Setting the dimension of component with fixed size is common and exactly the same size, regardless of screen dimensions.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class HeightWidth extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     powderblue:{  
    17.         width: 100, height: 100, backgroundColor: ‘powderblue’  
    18.     },  
    19.     skyblue:{  
    20.         width: 200, height: 200, backgroundColor: ‘skyblue’  
    21.     },  
    22.     steelblue:{  
    23.         height: 300, backgroundColor: ‘steelblue’  
    24.     },  
    25. })  

    Output

    React Native Height and Width

    Flex Dimensions

    The flex property styles the component to expand and shrink it dynamically according to available space. Setting flex: 1 will fill all the available space to the component, and shared evenly among the other components of same as the parent. Higher the flex value, occupy component higher ratio of space compared to its siblings.

    1.  import React, { Component } from ‘react’;  
    2. import { StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class HeightWidth extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.       flex:1  
    18.     },  
    19.     powderblue:{  
    20.         flex:1,  
    21.         backgroundColor: ‘powderblue’,  
    22.     },  
    23.     skyblue:{  
    24.         flex:2,  
    25.         backgroundColor: ‘skyblue’,  
    26.     },  
    27.     steelblue:{  
    28.         flex:3,  
    29.         backgroundColor: ‘steelblue’,  
    30.     },  
    31. })  

    Output

    React Native Height and Width
  • React Native Style

    React Native simply uses JavaScript for styling our core components. We don’t require any special language or syntax for defining styles. All the core components use a prop (property) named style. The style names and values are similar to CSS that works for the web. There is the only difference in the way of writing names using camel casing, e.g fontSize rather than font-size.

    The style prop is a plain old JavaScript object which is the simplest way for styling our code.

    There are different ways to design our component, by using inline style and by using StyleSheet.create. As the component increases in complexity, it is better to use StyleSheet.create to define several styles in one place.

    React Native style Example 1

    In this example, we will use both inline style as well as StyleSheet.create. Inline styles are applied at where the components are created.

    App.js

    1.  import React, { Component } from ‘react’;  
    2. import { AppRegistry, StyleSheet, Text, View } from ‘react-native’;  
    3.   
    4. export default class ImplementingStyle extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View>  
    8.                 <Text style={{ backgroundColor: ‘#a7a6a9’, color: ‘yellow’, fontSize: 20 }}>this is inline style</Text>  
    9.                 <Text style={styles.green}>just green</Text>  
    10.                 <Text style={styles.biggray}>just biggray</Text>  
    11.                 <Text style={[styles.biggray, styles.green]}>biggray, then green</Text>  
    12.                 <Text style={[styles.green, styles.biggray]}>green, then biggray</Text>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  
    17. const styles = StyleSheet.create({  
    18.     biggray: {  
    19.         color: ‘gray’,  
    20.         fontWeight: ‘bold’,  
    21.         fontSize: 30,  
    22.     },  
    23.     green: {  
    24.         color: ‘green’,  
    25.     },  
    26. });  

    Output

    React Native Style

    React Native style Example 2

    We can also use the external JavaScript file to style our application. In this example, we create external JS file and import it into our App.js file.

    StyleComponent.js

    1. import React, { Component } from ‘react’  
    2. import { Text, View, StyleSheet } from ‘react-native’  
    3.   
    4. const StyleComponent = (props) => {  
    5.     return (  
    6.         <View>  
    7.             <Text style = {styles.myState}>  
    8.                 {props.myState}  
    9.             </Text>  
    10.         </View>  
    11.     )  
    12. }  
    13. export default StyleComponent  
    14.   
    15. const styles = StyleSheet.create ({  
    16.     myState: {  
    17.         marginTop: 20,  
    18.         textAlign: ‘center’,  
    19.         color: ‘green’,  
    20.         fontWeight: ‘bold’,  
    21.         fontSize: 20  
    22.     }  
    23. })  

    App.js

    1.  import React from ‘react’;  
    2. import { StyleSheet, Text, View } from ‘react-native’;  
    3. import StyleComponent from ‘./StyleComponent’  
    4.   
    5. export default class App extends React.Component {  
    6.     state = {  
    7.         myState: ‘This is my state, style through external style’  
    8.     }  
    9.     render() {  
    10.         return (  
    11.             <View>  
    12.                 <StyleComponent myState = {this.state.myState}/>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  

    Output

    React Native Style
  • React Native Props

    The properties of React Native components are simply pronounced as props. In React Native, most of the components can be customized at the time of their creation with different parameters. These parameters are known as props. They are immutable, and they cannot be changed.

    One of the examples of props is a source property if Image component which controls the image is displayed over the device screen.

    React Native Default custom Props

    1.  import React, { Component } from ‘react’;  
    2. import {  
    3.   Platform,  
    4.   StyleSheet,  
    5.   Image,  
    6.   Text,  
    7.   View  
    8. } from ‘react-native’;  
    9.   
    10.   
    11. export default class App extends Component<{}> {  
    12.   render() {  
    13.     let imagePath = { uri: ‘https://facebook.github.io/react-native/img/header_logo.png’};  
    14.     return (  
    15.         <View style={styles.container}>  
    16.           <Text style={styles.welcome}>Welcome to React Native!</Text>  
    17.           <Image source={imagePath} style={{width: 250, height: 250}} />  
    18.         </View>  
    19.     );  
    20.   }  
    21. }  
    22.   
    23. const styles = StyleSheet.create({  
    24.   container: {  
    25.     flex: 1,  
    26.     justifyContent: ‘center’,  
    27.     alignItems: ‘center’,  
    28.     backgroundColor: ‘#a7a6a9’,  
    29.   },  
    30.   welcome: {  
    31.     fontSize: 30,  
    32.     textAlign: ‘center’,  
    33.     margin: 20,  
    34.   }  
    35. });  

    Output:

    React Native Props

    Using props in our own Component

    We can also use props in our components. A single component can be used in many different places in the app by making slightly different properties in each place. To implement the props in our component, this.props is applied followed by the property.

    For example, one of the basic React Native components is Text. When we create a Text component, we can use a prop “name” as props to control its appearance. We also apply the StyleSheet to the component which is used as our component.

    App.js

    1.  import React, { Component } from ‘react’;  
    2. import { StyleSheet, Text, View } from ‘react-native’;  
    3.   
    4. class ChildClass extends Component {  
    5.   render() {  
    6.     return (  
    7.         <View style={{alignItems: ‘center’}}>  
    8.           <Text style={styles.welcome}>Hello {this.props.name}!</Text>  
    9.         </View>  
    10.     );  
    11.   }  
    12. }  
    13.   
    14. export default class ParentsClass extends Component {  
    15.   render() {  
    16.     return (  
    17.         <View style={{alignItems: ‘center’}}>  
    18.           <ChildClass name=’Ashu’ />  
    19.           <ChildClass name=’Aman’ />  
    20.           <ChildClass name=’Max’ />  
    21.         </View>  
    22.     );  
    23.   }  
    24. }  
    25. const styles = StyleSheet.create({  
    26.    welcome: {  
    27.     fontSize: 30,  
    28.   }  
    29. });  
    30.   
    31. // skip this line if using Create React Native App  
    32. //AppRegistry.registerComponent(‘MyReactNativeApp’, () => ParentsClass);  

    Output:

    React Native Props
  • React Native State

    There are two types of data state and props in React Native which control the component. The component that uses the state is mutable. They can be changed later on if required. The props component is immutable, and it is fixed throughout the lifetime.

    The state is generally initialized in constructor and then call setState when we want to change it.

    React Native state Example 1

    In this example, we create a Text component with state data. The content of Text component will be updated by clicking on it. The event onPress call the setState, and it updates the state “myState” text.

    1.  import React, {Component} from ‘react’;  
    2. import { Text, View } from ‘react-native’;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         myState: ‘This is a text component, created using state data. It will change or updated on clicking it.’  
    7.     }  
    8.     updateState = () => this.setState({myState: ‘The state is updated’})  
    9.     render() {  
    10.         return (  
    11.             <View>  
    12.                 <Text onPress={this.updateState}> {this.state.myState} </Text>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  

    Output

    React Native State
    React Native State

    React Native state Example 2

    Let’s create another example of state data in which we interchange the Text value “Show” and “Hide” to show and hide the input password.

    Create three state variables that will be changed by clicking the Text component defined as a state. Clicking the Text component calls the handleToggle function, and the current state of Boolean variable “isPasswordVisible” is assigned in it. Here, if the condition checks the value of “isPasswordVisible” and proceeds accordingly.

    1.  import React, { Component } from ‘react’;  
    2. import {StyleSheet,Text,View,TextInput,TouchableOpacity} from ‘react-native’;  
    3.   
    4. export default class App extends Component {  
    5.     state: {  
    6.         password: string,  
    7.         isPasswordVisible: boolean,  
    8.         toggleText: string,  
    9.     }  
    10.     constructor(props: Props) {  
    11.         super(props);  
    12.         this.state = {  
    13.             password: ”,  
    14.             isPasswordVisible: true,  
    15.             toggleText: ‘Show’,  
    16.         };  
    17.     }  
    18.     handleToggle = () => {  
    19.         const { isPasswordVisible } = this.state;  
    20.         if (isPasswordVisible) {  
    21.             this.setState({ isPasswordVisible: false });  
    22.             this.setState({ toggleText: ‘Hide’ });  
    23.         } else {  
    24.             this.setState({ isPasswordVisible: true });  
    25.             this.setState({ toggleText: ‘Show’ });  
    26.         }  
    27.     };  
    28.     render() {  
    29.         return (  
    30.             <View style={styles.container}>  
    31.                 <TextInput  
    32.                     secureTextEntry={this.state.isPasswordVisible}  
    33.                     style={{ width: 400, height: 50, backgroundColor: ‘#a7a6a9’, color: ‘white’, fontSize: 20 }}  
    34.                 />  
    35.                 <TouchableOpacity onPress={this.handleToggle}>  
    36.                     <Text  style={{fontSize: 20}}>{this.state.toggleText}</Text>  
    37.                 </TouchableOpacity>  
    38.             </View>  
    39.         );  
    40.     }  
    41. }  
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: ‘center’,  
    46.         alignItems: ‘center’,  
    47.     }  
    48. });  

    Output

    React Native State
    React Native State
  • React Native View

    The View is the fundamental component of React Native for building a user interface. It is a container that supports layout with flexbox, style, touch handling, and accessibility controls. It maps directly to the native view similar to whatever platform on React Native app is running on. It displays the components regardless with UIView, <div>, android.view, etc.

    View component can be nested, contains other views inside it. It can contain 0 to many children of any type.

    Note: View(s) component used with StyleSheet makes it more clarity and well performed, however, it also supports inline styles

    Props of View

    onStartShouldSetResponderaccessibilityLabelaccessibilityHinthitSlop
    nativeIDonAccessibilityTaponLayoutonMagicTap
    onMoveShouldSetResponderonMoveShouldSetResponderCaptureonResponderGrantonResponderMove
    onResponderRejectonResponderReleaseonResponderTerminateonResponderTerminationRequest
    accessibleonStartShouldSetResponderCapturepointerEventsremoveClippedSubviews
    styletestIDaccessibilityComponentTypeaccessibilityLiveRegion
    collapsableimportantForAccessibilityneedsOffscreenAlphaCompositingrenderToHardwareTextureAndroid
    accessibilityRoleaccessibilityStatesaccessibilityTraitsaccessibilityViewIsModal
    accessibilityElementsHiddenaccessibilityIgnoresInvertColorsshouldRasterizeIOS

    React Native View Example

    In this example, we create a View component that contains two colored boxes and a text component in a row with height and width.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {StyleSheet,View, Text} from ‘react-native’  
    3.   
    4. export default class SwitchExample extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={{backgroundColor: ‘blue’, flex: 0.3}} />  
    9.                 <View style={{backgroundColor: ‘red’, flex: 0.5}} />  
    10.                 <Text style={{fontSize: 18}}>View Example</Text>  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create ({  
    16.      container: {  
    17.          flex: 1,  
    18.          flexDirection: ‘row’,  
    19.          height: 100,  
    20.          width: “80%”,  
    21.          backgroundColor:”#5ead97″  
    22.      }  
    23. })  

    Output:

    React Native View
  • First Application Hello World

    Let’s build our first React Native application on Windows as development operating system and Android as target operating system.

    Steps to create React Native application

    1. First, you have to start your emulator (Android Emulator) and make it live.

    2. Create a directory (ReactNative) in your any drive.

    3. Open “Command Prompt” and go to your ReactNative directory.

    4. Write a command react-native init FirstApp to initialize your app “FirstApp”.

    React Native First Application Hello World

    5. Go to your directory location “FirstApp” and run the command react-native run-android. It will start Node server and launch your application in virtual device emulator.

    React Native First Application Hello World
    React Native First Application Hello World

    Output:

    React Native First Application Hello World

    View Code of React Native Application

    Open your one of the favorite JavaScript supportable IDE and open App.js file inside your FirstApp application.

    React Native First Application Hello World

    Code of default React Native first app.

    App.js

    1.  import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text, View} from ‘react-native’;  
    3.   
    4. const instructions = Platform.select({  
    5.   ios: ‘Press Cmd+R to reload,\n’ + ‘Cmd+D or shake for dev menu’,  
    6.   android:  
    7.     ‘Double tap R on your keyboard to reload,\n’ +  
    8.     ‘Shake or press menu button for dev menu’,  
    9. });  
    10.   
    11. type Props = {};  
    12. export default class App extends Component<Props> {  
    13.   render() {  
    14.     return (  
    15.       <View style={styles.container}>  
    16.         <Text style={styles.welcome}>Welcome to React Native!</Text>  
    17.         <Text style={styles.instructions}>To get started, edit App.js</Text>  
    18.         <Text style={styles.instructions}>{instructions}</Text>  
    19.       </View>  
    20.     );  
    21.   }  
    22. }  
    23.   
    24. const styles = StyleSheet.create({  
    25.   container: {  
    26.     flex: 1,  
    27.     justifyContent: ‘center’,  
    28.     alignItems: ‘center’,  
    29.     backgroundColor: ‘#F5FCFF’,  
    30.   },  
    31.   welcome: {  
    32.     fontSize: 20,  
    33.     textAlign: ‘center’,  
    34.     margin: 10,  
    35.   },  
    36.   instructions: {  
    37.     textAlign: ‘center’,  
    38.     color: ‘#333333’,  
    39.     marginBottom: 5,  
    40.   },  
    41. });  

    index.js

    1. /** @format */  
    2.   
    3. import {AppRegistry} from ‘react-native’;  
    4. import App from ‘./App’;  
    5. import {name as appName} from ‘./app.json’;  
    6.   
    7. AppRegistry.registerComponent(appName, () => App);  

    Create a simple React Native “Hello World” application

    Create a simple “Hello World” app by editing App.js file of FirstApp.

    Save the application and reload by simply pressing twice “R” or Ctrl+M (Reload).

    App.js

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text, View} from ‘react-native’;  
    3.   
    4. type Props = {};  
    5. export default class App extends Component<Props> {  
    6.   render() {  
    7.     return (  
    8.       <View>  
    9.         <Text>Hello World</Text>  
    10.       </View>  
    11.     );  
    12.   }  
    13. }  

    Output:

    React Native First Application Hello World

    Edit simple React Native “Hello World” application

    Edit React Native “Hello World” application using StyleSheet.

    App.js

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text, View} from ‘react-native’;  
    3.   
    4. type Props = {};  
    5. export default class App extends Component<Props> {  
    6.   render() {  
    7.     return (  
    8.       <View>  
    9.         <Text style={styles.welcome}>Hello World</Text>  
    10.       </View>  
    11.     );  
    12.   }  
    13. }  
    14. const styles = StyleSheet.create({  
    15.   welcome: {  
    16.     fontSize: 20,  
    17.     textAlign: ‘center’,  
    18.     margin: 10,  
    19.   }  
    20. });  

    Output:

    React Native First Application Hello World

    React Native Code Explanation

    • import React, {Component} from ‘react’: imports the library and other components from react module and assign then to variable React.
    • const instruction: sets to display the platform-specific message.
    • export default class App extends Component:defines the classes that extend the React Component. The export default class modifier makes the class “public”. This block of code defines the components that represent the user interface.
    • render(): a function that returns a React element.
    • return(): returns the result of layout and UI components.
    • View: a container that supports the layout accessibility controls. It is a fundamental component for building the UI.
    • Text: a React component for displaying text.
    • style: a property used for styling the components using StyleSheet.
    • styles: used to design individual components.
    • {styles.instructions}>{instructions}:
    • const styles = StyleSheet.create({}): The StyleSheet class creates the style object that controls the layout and appearance of components. It is similar to Cascading Style Sheets (CSS) used on the Web.
  • Environment Setups

    There is a different alternative for React Native environment setup (installation), depends upon the operating system you use.

    The instructions are quite different for each development and target operating system.

    In this tutorial, we will use Windows as a development operating system and Android as a target operating system.

    Developing app using React Native framework requires Node, React Native command line interface, Python2, JDK, and Android Studio.

    Here, we are using a favorite package manager Chocolatey for Windows. Using this, we can install a recent version of Python, and Java SE Development Kit (JDK).


    Steps to Setup React Native Environment

    1. Visit Chocolatey, and click “Install Chocolatey Now” it open another URL.

    React Native Environment Setup

    2. Install chocolatey setup, copy the code provided in Install with cmd.exe section.

    1. @”%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe” -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command “iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’))” && SET “PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin”  
    React Native Environment Setup

    3. Open your Command Prompt in Administrative mode (right-click Command Prompt and select “Run as Administrator”), paste this code and click enter. It will install Chocolatey.

    React Native Environment Setup

    4. In the Administrative mode of command prompt, paste the code and run it (install Node.js, Python, and JDK).

    If you have already installed Node.js, make sure it has version above 8 and if you have already installed JDK, make it version 8 or newer version.

    1. choco install -y nodejs.install python2 jdk8  
    React Native Environment Setup

    5. Node comes with npm (Node Package Manager), which lets you install the React Native. Run the given code:

    1. npm install -g react-native-cli  
    React Native Environment Setup

    Setup Android Studio

    1. Visit Android website and download Android Studio.

    React Native Environment Setup

    2. Run the downloaded android studio set (.exe) file and follow the instruction.

    React Native Environment Setup

    3. Choose the feature you want to install.

    React Native Environment Setup

    4. Select the installation location.

    React Native Environment Setup

    5. Let the installation proceed and click Next.

    React Native Environment Setup

    6. Click Finish to complete the installation.

    React Native Environment Setup

    After successful installation, the Android Studio home screen will appear.

    React Native Environment Setup

    Setup Java JDK and Android SDK path

    1. Visit How to set path in Java to set JDK path.

    2. Set Android SDK path as My Computer > Properties > Advance system settings > Environment Variables > in System variables section. Click “New…” add Android home and Android SDK as bellow screen.

    React Native Environment Setup

    3. Install the required components, go to Tools Android > SDK Manager > SDK platforms and select the required components and install.

    React Native Environment Setup

    4. Let the installation proceed and after successfully installation, click Finish.

    React Native Environment Setup

    5. Create Android Emulator, a virtual Android Device, go to Tools > Android > AVD Manager > Create Virtual Device… SDK platforms and select the device type.

    React Native Environment Setup

    6. Select API level of Android Emulator.

    React Native Environment Setup

    7. Provide device name and set properties by clicking Show Advance Settings.

    React Native Environment Setup

    8. Launch the Emulator.

    React Native Environment Setup
  • React Native Tutorial

    React Native Tutorial provides basic and advanced concepts of Discrete mathematics. Our React Native Tutorial is designed for beginners and professionals both.

    React Native is a JavaScript Framework which is used to develop mobile applications for iOS and Android.

    Our React Native tutorial includes all the topics which help to learn TypeScript. These are React Native Introduction, Environment Setup, First App Hello World, State, Flexbox, Height and Width, TextInput etc.

    What is React Native?

    React Native is a JavaScript framework used for developing a real, native mobile application for iOS and Android. It uses only JavaScript to build a mobile application. It is like React, which uses native component rather than using web components as building blocks.

    Note: React Native is a JavaScript framework whereas ReactJs (React.js) is a JavaScript library.

    React Native is based on React, JavaScript library of Facebook, and XML-esque markup (JSX) for developing the user interface. It targets the mobile platform rather than the browser.

    What are React Native apps?

    React Native apps are not web application. They are running on a mobile device, and it does not load over the browser. It is also not a Hybrid app that builds over Ionic, Phone Gap, etc. that runs over WebView component. React Native apps are the real native app, the JavaScript code stays as JavaScript, and they run in some extra thread by the compiled app. The user interface and everything are compiled to native code.

    History of React Native

    Facebook develops the React Native in 2013 for their internal project Hackathon. Later on, it was released publically in January 2015 as React.js, and in March 2015, Facebook announced that React Native is open and available on GitHub.

    React Native was initially developed for the iOS application. However, recently it also supports the Android operating system.

    Advantages of React Native

    There are several advantages of React Native for building mobile applications. Some of them are given below:

    1. Cross-Platform Usage: Provide facility of “Learn once write everywhere”, it works for both platform Android as well iOS devices.
    2. Class Performance: The code written in React Native are compiled into native code, which enables it for both operating systems as well as it functions in the same way on both the platforms.
    3. JavaScript: The JavaScript knowledge is used to build native mobile apps.
    4. Community: The large community of React and React Native around helps us to find any answer we require.
    5. Hot Reloading: Making a few changes in the code of your app will be immediately visible during development. If business logic is changed, its reflection is live reloaded on screen.
    1. Improving with Time: Some features of iOS and Android are still not supported, and the community is always inventing the best practices.
    2. Native Components: We will need to write some platform specific code if we want to create native functionality which is not designed yet.
    3. Existence is Uncertain: As the Facebook develop this framework, its presence is uncertain since it keeps all the rights to kill off the project anytime. As the popularity of React Native rises, it is unlikely to happen.

    Prerequisite

    Before learning React Native, you must have the knowledge of OOPs concept and JavaScript.

    Audience

    We have developed this React Native tutorial for beginners and professionals both.

    Problems

    We assure you that you will not find any problem in our React Native tutorial. But, if you find any mistake, you can post it in our comment section.