Author: saqibkhan

  • Passing Value between Screen

    While creating an app containing multiple screens, then sometimes it is required to pass value between one screen to another. This can be achieved by using this.props.navigation.navigate() function.

    This function is used to navigate between the different screens.

    Before diving into this example, you need to first go through React Native Navigation.

    Example

    In this example, we will input the value in the first screen and get it into the second screen.

    The value (param) is passed as an object in the first screen to the navigation.navigate function as:

    1. this.props.navigation.navigate(‘RouteName’, { /* params go here */ })   

    The same value (param) is read in the second screen as:

    1. this.props.navigation.getParam(paramName, defaultValue)   

    Create a HomeScreen.js file and add a TextInput component for input value and a Button to submit. The TextInput component has an onChangeText prop which takes a function which is to be called whenever the text changed.

    HomeScreen.js

    1. import React from ‘react’;  
    2. //import react in our code.  
    3. import { StyleSheet, View, Button, TextInput } from ‘react-native’;  
    4.   
    5. export default class HomeScreen extends React.Component {  
    6.   
    7.     constructor(props) {  
    8.         //constructor to set default state  
    9.         super(props);  
    10.         this.state = {  
    11.             username: ”,  
    12.         };  
    13.     }  
    14.     static navigationOptions = {  
    15.         title: ‘Home’,  
    16.         headerStyle: {  
    17.             backgroundColor: ‘#f4511e’,  
    18.         },  
    19.         //headerTintColor: ‘#0ff’,  
    20.         headerTitleStyle: {  
    21.             fontWeight: ‘bold’,  
    22.         },  
    23.     };  
    24.   
    25.     render() {  
    26.         const { navigate } = this.props.navigation;  
    27.         return (  
    28.             //View to hold our multiple components  
    29.             <View style={styles.container}>  
    30.             {/*Input to get the value from the user*/}  
    31.             <TextInput  
    32.         value={this.state.username}  
    33.         onChangeText={username => this.setState({ username })}  
    34.         placeholder={‘Enter Any value’}  
    35.         style={styles.textInput}  
    36.         />  
    37.         <View style={styles.buttonStyle}>  
    38.             <Button  
    39.         title=”Submit”  
    40.         // color=”#00B0FF”  
    41.         onPress={() =>  
    42.         this.props.navigation.navigate(‘Profile’, {  
    43.             userName: this.state.username,  
    44.             otherParam: ‘101’,  
    45.         })  
    46.     }  
    47.         />  
    48.         </View>  
    49.         </View>  
    50.     );  
    51.     }  
    52. }  
    53. const styles = StyleSheet.create({  
    54.     container: {  
    55.         flex: 1,  
    56.         backgroundColor: ‘#fff’,  
    57.         alignItems: ‘center’,  
    58.         padding: 16,  
    59.     },  
    60.     textInput: {  
    61.         height: 45,width: “95%”,borderColor: “gray”,borderWidth: 1,fontSize:20,  
    62.     },  
    63.     buttonStyle:{  
    64.         width: “93%”,  
    65.         marginTop: 50,  
    66.         backgroundColor: “red”,  
    67.     }  
    68. });  

    In the above code userName: this.state.username, store the value input into the TextInput component and otherParam: ‘101’ directly assign a value. On clicking the Button userName and otherParam is passed to Profile screen.

    ProfileScreen.js

    In this screen, we receive the value of userName and otherParam using navigation.getParam(‘paramValue’, default value) and stored into object user_name and other_param respectively. The value of JavaScript object is converted to string using JSON.stringify(object) function.

    1. import React from ‘react’;  
    2. import { StyleSheet, View, Text, Button } from ‘react-native’;  
    3.   
    4. export default class ProfileScreen extends React.Component {  
    5.     static navigationOptions = {  
    6.         title: ‘Profile’,  
    7.         headerStyle: {  
    8.             backgroundColor: ‘#f4511e’,  
    9.         },  
    10.         //headerTintColor: ‘#0ff’,  
    11.         headerTitleStyle: {  
    12.             fontWeight: ‘bold’,  
    13.         },  
    14.     };  
    15.     render() {  
    16.         {/*Using the navigation prop we can get the 
    17.               value passed from the previous screen*/}  
    18.         const { navigation } = this.props;  
    19.         const user_name = navigation.getParam(‘userName’, ‘NO-User’);  
    20.         const other_param = navigation.getParam(‘otherParam’, ‘some default value’);  
    21.         return (  
    22.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    23.                 <Text style={{ marginTop: 16,fontSize: 20,}}>  
    24.                     This is Profile Screen and we receive value from Home Screen  
    25.                 </Text>  
    26.                 <Text style={styles.textStyle}>User Name: {JSON.stringify(user_name)}</Text>  
    27.                 <Text style={styles.textStyle}>Other Param: {JSON.stringify(other_param)}</Text>  
    28.                 <View style={styles.buttonStyle}>  
    29.                 <Button  
    30.                     title=”Go back”  
    31.                     onPress={() => this.props.navigation.goBack()}  
    32.                 />  
    33.                 </View>  
    34.             </View>  
    35.         );  
    36.     }  
    37. }  
    38. const styles = StyleSheet.create({  
    39.     textStyle: {  
    40.         fontSize: 23,  
    41.         textAlign: ‘center’,  
    42.         color: ‘#f00’,  
    43.     },  
    44.   
    45.     buttonStyle:{  
    46.         width: “93%”,  
    47.         marginTop: 50,  
    48.         backgroundColor: “red”,  
    49.     }  
    50. });  

    App.js

    Create the App.js file as it is the entry point of the app and imports the HomeScreen and ProfileScreen. The HomeScreen set as the first screen using the initialRouteName.

    1. import React from ‘react’;  
    2. import {createStackNavigator,createAppContainer} from ‘react-navigation’;  
    3. import HomeScreen from ‘./HomeScreen’;  
    4. import ProfileScreen from ‘./ProfileScreen’;  
    5.   
    6. const AppNavigator = createStackNavigator(  
    7.     {  
    8.         Home: HomeScreen,  
    9.         Profile: ProfileScreen  
    10.     },  
    11.     {  
    12.         initialRouteName: “Home”  
    13.     }  
    14. );  
    15. export default createAppContainer(AppNavigator);  

    Output:

    React Native Passing Value between Screen
    React Native Passing Value between Screen
    React Native Passing Value between Screen
    React Native Passing Value between Screen

    We also send and receive the parameters into JSON such as:

    HomeScreen.js

    1. onPress={() =>  
    2.     navigate(‘Profile’, {  
    3.         JSON_ListView_Clicked_Item: this.state.username,  
    4.     })  
    5. }  

    ProfileScreen.js

    This screen read the value in two ways without checking.

    1. {this.props.navigation.state.params.JSON_ListView_Clicked_Item}  

    Or checking the input value is null or not

    1. {this.props.navigation.state.params.JSON_ListView_Clicked_Item  
    2.    ? this.props.navigation.state.params.JSON_ListView_Clicked_Item  
    3.     : ‘No Value Passed’}  

    1. <Text style={styles.textStyle}>  
    2.         {this.props.navigation.state.params.JSON_ListView_Clicked_Item}  
    3.     </Text>  
    4. <Text style={{ marginTop: 16,fontSize: 20, }}>With Check</Text>  
    5.     {/*If you want to check the value is passed or not, 
    6.             you can use conditional operator.*/}  
    7. <Text style={styles.textStyle}>  
    8.     {this.props.navigation.state.params.JSON_ListView_Clicked_Item  
    9.         ? this.props.navigation.state.params.JSON_ListView_Clicked_Item  
    10.         : ‘No Value Passed’}  

    Output:

    React Native Passing Value between Screen
    React Native Passing Value between Screen
    React Native Passing Value between Screen
    React Native Passing Value between Screen
  • Moving Between Screens

    In this section, we will discuss how to navigate from one route screen to another route screen and come back to the initial route. In the previous part of Navigation, we created the stack navigator with two route screens (Home and Profile).

    Moving from one screen to another is performed by using the navigation prop, which passes down our screen components. It is similar to write the below code for a web browser:

    1. <a href=”profiles.html”>Go to Profile</a>  

    The other way to write this would be:

    1. <a onClick={() => { document.location.href = “profile.html”; }}>Go to Profile</a>  

    Navigate to the new screen

    Navigation from one screen to another screen is performed in different ways:

    1. <Button  
    2.           title=”Go to URL”  
    3.           onPress={() => this.props.navigation.navigate(‘url’)}  
    4.         />  

    App.js

    Add a Button component in ‘HomeScreen’ and perform an onPress{} action which calls the this.props.navigation.navigate(‘Profile’) function. Clicking the Button component moves screen to ‘ProfileScreen’ layout.

    1. import React from ‘react’;  
    2. import { View, Text, Button } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     render() {  
    7.         return (  
    8.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    9.                 <Text>Home Screen</Text>  
    10.                 <Button  
    11.                     title=”Go to Profile”  
    12.                     onPress={() => this.props.navigation.navigate(‘Profile’)}  
    13.                 />  
    14.             </View>  
    15.         );  
    16.     }  
    17. }  
    18. class ProfileScreen extends React.Component {  
    19.     render() {  
    20.         return (  
    21.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    22.                 <Text>Profile Screen</Text>  
    23.             </View>  
    24.     );  
    25.     }  
    26. }  
    27.   
    28. const AppNavigator = createStackNavigator(  
    29.     {  
    30.         Home: HomeScreen,  
    31.         Profile: ProfileScreen  
    32.     },  
    33.     {  
    34.         initialRouteName: “Home”  
    35.     }  
    36. );  
    37.   
    38. const AppContainer = createAppContainer(AppNavigator);  
    39. export default class App extends React.Component {  
    40.     render() {  
    41.         return <AppContainer />;  
    42.     }  
    43. }  

    Output:

    React Native Moving Between Screens
    React Native Moving Between Screens
    • this.props.navigation: The navigation prop is passed the every screen component in stack navigation.
    • navigate(‘Profile’): Call the navigate function with the route name where we want to move.

    Navigate to a route screen multiple times

    Adding navigation from ‘ProfileScreen’ to ‘Profile’ URL doesn’t make any change because we are already at Profile route.

    1. class ProfileScreen extends React.Component {  
    2.     render() {  
    3.         return (  
    4.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    5.                 <Text>Profile Screen</Text>  
    6.                    <Button  
    7.                      title=”Go to Profile”  
    8.                      onPress={() => this.props.navigation.navigate(‘Profile’)}  
    9.                    />  
    10.              </View>  
    11.     );  
    12.     }  
    13. }  

    To call the profiles screen, mainly in the case of passing unique data (params) to each route. To do this, we change navigate to push. The navigate push expresses the intent to add another route disregarding the existing navigation history.

    1. <Button  
    2.         title=”Go to Profile”  
    3.          onPress={() => this.props.navigation.push(‘Profile’)}  
    4. />  

    On pressing the button call push method each time and add a new route to the navigation stack.

    Going back

    The header of stack navigator automatically includes a back button when there is a possibility to go back from the current screen. The single screen stack navigation doesn’t provide the back button as there is nothing where we can go back.

    Sometimes, we programmatically implement the back behavior, for that we can call this.props.navigation.goBack(); function.

    App.js

    1. import React from ‘react’;  
    2. import { View, Text, Button } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     render() {  
    7.         return (  
    8.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    9.                 <Text>Home Screen</Text>  
    10.                 <Button  
    11.                     title=”Go to Profile”  
    12.                     onPress={() => this.props.navigation.push(‘Profile’)}  
    13.                 />  
    14.             </View>  
    15.         );  
    16.     }  
    17. }  
    18. class ProfileScreen extends React.Component {  
    19.     render() {  
    20.         return (  
    21.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    22.                 <Text>Profile Screen</Text>  
    23.                 <Button  
    24.                     title=”Go to Profile… again”  
    25.                     onPress={() => this.props.navigation.push(‘Profile’)}  
    26.                 />  
    27.                 <Button  
    28.                     title=”Go to Home”  
    29.                     onPress={() => this.props.navigation.navigate(‘Home’)}  
    30.                  />  
    31.                 <Button  
    32.                     title=”Go back”  
    33.                     onPress={() => this.props.navigation.goBack()}  
    34.                 />  
    35.             </View>  
    36.     );  
    37.     }  
    38. }  
    39.   
    40. const AppNavigator = createStackNavigator(  
    41.     {  
    42.         Home: HomeScreen,  
    43.         Profile: ProfileScreen  
    44.     },  
    45.     {  
    46.         initialRouteName: “Home”  
    47.     }  
    48. );  
    49.   
    50. const AppContainer = createAppContainer(AppNavigator);  
    51. export default class App extends React.Component {  
    52.     render() {  
    53.         return <AppContainer />;  
    54.     }  
    55. }  

    Output:

    React Native Moving Between Screens
    React Native Moving Between Screens
  • React Native Configuring Header Bar

    The static property of a screen component is called navaigationOptions. It is either an object or a function. It returns an object containing several configuration options.

    Props of the header bar

    PropsDescription
    titleIt sets the title of active screen.
    headerStyleIt adds style to header bar.
    backgroundColorIt sets the background color of the header bar.
    headerTintColorIt sets the color to header title.
    headerTitleStyleIt adds style to the title of a screen.
    fontWeightIt sets the font style of header title.

    1. static navigationOptions = {  
    2.     title: ‘HeaderTitle’,  
    3.     headerStyle: {  
    4.         backgroundColor: ‘#f4511e’,  
    5.     },  
    6.     headerTintColor: ‘#0ff’,  
    7.     headerTitleStyle: {  
    8.        fontWeight: ‘bold’,  
    9.     },  
    10. };  

    React Native Moving from One Screen to Other Example 1

    In this example, we create two screen named as ‘Home’ and ‘Profile’. The Home screen is set as first screen using “initialRouteName” property and Profile screen as second.

    App.js

    1. import React from ‘react’;  
    2. import { View, Text, Button } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     static navigationOptions = {  
    7.         title: ‘Home’,  
    8.         headerStyle: {  
    9.             backgroundColor: ‘#f4511e’,  
    10.         },  
    11.         //headerTintColor: ‘#0ff’,  
    12.         headerTitleStyle: {  
    13.             fontWeight: ‘bold’,  
    14.         },  
    15.     };  
    16.   
    17.     render() {  
    18.         return (  
    19.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    20.                 <Text>Home Screen</Text>  
    21.                 <Button  
    22.                     title=”Go to Profile”  
    23.                     onPress={() => this.props.navigation.push(‘Profile’)}  
    24.                 />  
    25.             </View>  
    26.         );  
    27.     }  
    28. }  
    29. class ProfileScreen extends React.Component {  
    30.     static navigationOptions = {  
    31.         title: ‘Profile’,  
    32.         headerStyle: {  
    33.             backgroundColor: ‘#f4511e’,  
    34.         },  
    35.         headerTintColor: ‘#0ff’,  
    36.         headerTitleStyle: {  
    37.             fontWeight: ‘bold’,  
    38.         },  
    39.     };  
    40.     render() {  
    41.         return (  
    42.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    43.                 <Text>Profile Screen</Text>  
    44.                 <Button  
    45.                     title=”Go to Profile… again”  
    46.                     onPress={() => this.props.navigation.push(‘Profile’)}  
    47.                 />  
    48.                 <Button  
    49.                     title=”Go to Home”  
    50.                     onPress={() => this.props.navigation.navigate(‘Home’)}  
    51.                  />  
    52.                 <Button  
    53.                     title=”Go back”  
    54.                     onPress={() => this.props.navigation.goBack()}  
    55.                 />  
    56.             </View>  
    57.     );  
    58.     }  
    59. }  
    60.   
    61. const AppNavigator = createStackNavigator(  
    62.     {  
    63.         Home: HomeScreen,  
    64.         Profile: ProfileScreen  
    65.     },  
    66.     {  
    67.         initialRouteName: “Home”  
    68.     }  
    69. );  
    70.   
    71. const AppContainer = createAppContainer(AppNavigator);  
    72. export default class App extends React.Component {  
    73.     render() {  
    74.         return <AppContainer />;  
    75.     }  
    76. }  

    Output:

    React Native Configuring Header Bar
    React Native Configuring Header Bar

    Using params in the title

    To use the params (parameter) as a title, we need to make navigationOptions as a function which returns a configuration object. Use the this.props inside the navigationOptions. As it is the static property of component “this” does not refer to an instance of componen and therefore no props are available.

    Making navigationOptions as a function which returns the object containing {navigation, navigationOptions, screenProps }. The navigation is the object which is passed to screen props as this.props.navigation. We can also get the params from navigation using navigation.getParam or navigation.state.params.

    1. class ProfileScreen extends React.Component {  
    2.     static navigationOptions = ({ navigation }) => {  
    3.         return {  
    4.             title: navigation.getParam(‘otherParam’, ‘A Param Header’),  
    5.         };  
    6.     };  
    7. }  

    The navigationOtions configuration of the active screen which can also be updated from the current screen component itself.

    1. //inside render   
    2. <Button  
    3.     title=”Update the title”  
    4.     onPress={() => this.props.navigation.setParams({otherParam: ‘Header Updated!’})}  
    5. />  

    Complete code

    In this example, we create two screen “Home” and “Profile”. The Profile screen set its header title using params as: title: navigation.getParam(‘otherParam’, ‘A Param Header’)

    App.js

    1. import React from ‘react’;  
    2. import { View, Text, Button } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     static navigationOptions = {  
    7.         title: ‘Home’,  
    8.         headerStyle: {  
    9.             backgroundColor: ‘#f4511e’,  
    10.         },  
    11.         //headerTintColor: ‘#0ff’,  
    12.         headerTitleStyle: {  
    13.             fontWeight: ‘bold’,  
    14.         },  
    15.     };  
    16.   
    17.     render() {  
    18.         return (  
    19.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    20.                 <Text>Home Screen</Text>  
    21.                 <Button  
    22.                     title=”Go to Profile”  
    23.                     onPress={() => this.props.navigation.push(‘Profile’)}  
    24.                 />  
    25.             </View>  
    26.         );  
    27.     }  
    28. }  
    29. class ProfileScreen extends React.Component {  
    30.     static navigationOptions = ({ navigation }) => {  
    31.         return {  
    32.             title: navigation.getParam(‘otherParam’, ‘A Param Header’),  
    33.         };  
    34.     };  
    35.   
    36.     render() {  
    37.         return (  
    38.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    39.                 <Text>Profile Screen</Text>  
    40.                 <Button  
    41.                     title=”Go back”  
    42.                     onPress={() => this.props.navigation.goBack()}  
    43.                 />  
    44.                 <Button  
    45.                     title=”Update the title”  
    46.                     onPress={() => this.props.navigation.setParams({otherParam: ‘Header Updated!’})}  
    47.                 />  
    48.             </View>  
    49.     );  
    50.     }  
    51. }  
    52.   
    53. const AppNavigator = createStackNavigator(  
    54.     {  
    55.         Home: HomeScreen,  
    56.         Profile: ProfileScreen  
    57.     },  
    58.     {  
    59.         initialRouteName: “Home”  
    60.     }  
    61. );  
    62.   
    63. const AppContainer = createAppContainer(AppNavigator);  
    64. export default class App extends React.Component {  
    65.     render() {  
    66.         return <AppContainer />;  
    67.     }  
    68. }  
    React Native Configuring Header Bar
    React Native Configuring Header Bar
    React Native Configuring Header Bar
  • React Native Navigation

    React Native Navigation is used for managing the presentation, and transition between multiple screens. There are two types of navigation built in mobile applications. These are stack navigation and tabbed navigation patterns.

    React Navigation Installation

    React Navigation is generated from React Native community that provides the navigation solution written in JavaScript.

    Create the React Native project and install the required packages and dependencies.

    Install the react-navigation package in React Native project using any one of the below command.

    1. yarn add react-navigation  
    2. # or with npm  
    3. # npm install –save react-navigation  

    After successful execution of the above command, it adds the “react-navigation”: “^3.3.0” (3.3.0 is version) in package.json file.

    After that, install react-native-gesture-handler package.

    1. yarn add react-native-gesture-handler  
    2. # or with npm  
    3. # npm install –save react-native-gesture-handler  

    Now, link all the native dependencies together using command:

    1. react-native link react-native-gesture-handler  

    To complete the installation of ‘react-native-gesture-handler’ for Android, make the following modification in MainActivity.java.

    projectDirectory/android/app/src/main/java/com/project/MainActivity.java

    1. import com.facebook.react.ReactActivityDelegate;  
    2. import com.facebook.react.ReactRootView;  
    3. import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;  
    4.   
    5. . . .  
    6.   
    7. @Override  
    8. protected ReactActivityDelegate createReactActivityDelegate() {  
    9.     return new ReactActivityDelegate(this, getMainComponentName()) {  
    10.         @Override  
    11.         protected ReactRootView createRootView() {  
    12.             return new RNGestureHandlerEnabledRootView(MainActivity.this);  
    13.         }  
    14.     };  
    15. }  

    Creating a stack navigator

    To create a stack navigation, we import createStackNavigator and createAppContainer functions of react-navigation library.

    App.js

    1. import React from “react”;  
    2. import {Button, View, Text } from “react-native”;  
    3. import { createStackNavigator, createAppContainer } from “react-navigation”;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     render() {  
    7.         return (  
    8.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    9.                 <Text>Home Screen</Text>  
    10.             </View>  
    11.         );  
    12.     }  
    13. }  
    14.   
    15. const AppNavigator = createStackNavigator({  
    16.     Home: {  
    17.         screen: HomeScreen  
    18.     }  
    19. });  
    20. export default createAppContainer(AppNavigator);  

    The createStackNavigator is a function which takes a route configuration object and options object. It returns the React component.

    MainActivity.java

    1. package com.naviexe;  
    2.   
    3. import com.facebook.react.ReactActivity;  
    4. import com.facebook.react.ReactActivityDelegate;  
    5. import com.facebook.react.ReactRootView;  
    6. import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;  
    7.   
    8. public class MainActivity extends ReactActivity {  
    9.   
    10.     @Override  
    11.     protected String getMainComponentName() {  
    12.         return “naviExe”;  
    13.     }  
    14.     @Override  
    15.     protected ReactActivityDelegate createReactActivityDelegate() {  
    16.         return new ReactActivityDelegate(this, getMainComponentName()) {  
    17.             @Override  
    18.             protected ReactRootView createRootView() {  
    19.                 return new RNGestureHandlerEnabledRootView(MainActivity.this);  
    20.             }  
    21.         };  
    22.     }  
    23. }  

    When we run the above code, we see an empty navigation bar containing the HomeScreen component.

    Output:

    React Native Navigation

    Shorthand route configuration

    When we have only a single screen as route that is Home screen component, we do not need to use the {screen: HomeScreen} , we can directly use the home component.

    1. const AppNavigator = createStackNavigator({  
    2.     Home: HomeScreen  
    3. });  

    Adding title and styling navigation

    1. static navigationOptions = {  
    2.     title: ‘Home’,  
    3.     headerStyle: {  
    4.         backgroundColor: ‘#f4511e’,  
    5.     },  
    6.     headerTintColor: ‘#0ff’,  
    7.     headerTitleStyle: {  
    8.        fontWeight: ‘bold’,  
    9.     },  
    10. };  

    1. import React from ‘react’;  
    2. import { View, Text } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     static navigationOptions = {  
    7.         title: ‘Home’,  
    8.         headerStyle: {  
    9.             backgroundColor: ‘#f4511e’,  
    10.         },  
    11.       //  headerTintColor: ‘#0ff’,  
    12.         headerTitleStyle: {  
    13.            fontWeight: ‘bold’,  
    14.         },  
    15.     };  
    16.     render() {  
    17.         return (  
    18.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    19.                 <Text>Home Screen</Text>  
    20.             </View>  
    21.         );  
    22.     }  
    23. }  
    24. const AppNavigator = createStackNavigator({  
    25.     Home: HomeScreen  
    26. });  
    27.   
    28. export default createAppContainer(AppNavigator);  

    Adding a second route screen

    Create another class (ProfileScreen) in App.js file to add the second route screen to the stack navigator.

    1. class ProfileScreen extends React.Component {  
    2.     render() {  
    3.         return (  
    4.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    5.                 <Text>Details Screen</Text>  
    6.             </View>  
    7.         );  
    8.     }  
    9. }  
    10.   
    11. const AppNavigator = createStackNavigator(  
    12.     {  
    13.         Home: HomeScreen,  
    14.         Profile: ProfileScreen  
    15.     },  
    16.     {  
    17.         initialRouteName: “Home”  
    18.     }  
    19. );  

    The initialRouteName options object specifies the initial route in the stack navigation.

    Complete code:

    App.js

    1. import React from ‘react’;  
    2. import { View, Text } from ‘react-native’;  
    3. import { createStackNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     render() {  
    7.         return (  
    8.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    9.                 <Text>Home Screen</Text>  
    10.             </View>  
    11.         );  
    12.     }  
    13. }  
    14. class ProfileScreen extends React.Component {  
    15.     render() {  
    16.         return (  
    17.             <View style={{ flex: 1, alignItems: “center”, justifyContent: “center” }}>  
    18.                 <Text>Details Screen</Text>  
    19.             </View>  
    20.         );  
    21.     }  
    22. }  
    23.   
    24. const AppNavigator = createStackNavigator(  
    25.     {  
    26.         Home: HomeScreen,  
    27.         Profile: ProfileScreen  
    28.     },  
    29.     {  
    30.         initialRouteName: “Home”  
    31.     }  
    32. );  
    33.   
    34. export default createAppContainer(AppNavigator);  

    Output:

    React Native Navigation
  • React Native Image

    The Image component is used to display the image on the screen. The image can be loaded from different source such as static resources, temporary local files, local disc, network images, etc.

    Static Image Resources

    The static images are added in app by placing it in somewhere in the source code directory and provide its path as:

    1. <Image source={require(‘./icon_name.png’)} />  

    In the above syntax, the packager will look for icon_name.png in the same folder as the component that requires it. To load the image on a specific platform, it should be named by specifying the platform as extensions such as icon_name.ios.png and icon_name.android.png.

    Images from Hybrid App’s Resources

    The hybrid app which is built (UI) by using both React Native and platform code can also uses the image which is bundled into the app.

    The image included through Xcode asset catalogs or in Android drawable folder are consumes without their extension.

    1. <Image source={{uri: ‘icon_name’}} style={{width: 60, height: 60}} />  

    The images within the Android assets folder, use the scheme: asset:/ with image extension.

    1. <Image source={{uri: ‘asset:/icon_name.png’}} style={{width: 60, height: 60}} />  

    Network Images

    The dynamic and network images are also be displayed in the Image component. To access the network image, it is required to specify the dimensions of image manually.

    It is recommended to use https in order to satisfy the App Transport Security requirements on iOS.

    1. // GOOD  
    2. <Image source={{uri: ‘https://url_of_image.png’}}  
    3.        style={{width: 60, height: 60}} />  
    4.   
    5. // BAD  
    6. <Image source={{uri: ‘https://url_of_image.png’}} />  

    Uri Data Images

    The encoded image data use the “data:” uri scheme in the image component. The data image also required to specify the dimension of the image.

    1. <Image  
    2.     style={{width: 66, height: 66}}  
    3.     source={{uri: ‘data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==’}}  
    4. />  

    Background Image via Nesting

    The background image is set using the ImageBackground component. It is also the same props as Image. We can add any component as children on the top of it.

    1. return (  
    2.   <ImageBackground source={…} style={{width: ‘100%’, height: ‘100%’}}>  
    3.     <Text>Inside</Text>  
    4.   </ImageBackground>  
    5. );  

    React Native Image Example

    App.js

    1. import React, { Component } from ‘react’;  
    2. import {StyleSheet, AppRegistry,Text, View, Image,ImageBackground } from ‘react-native’;  
    3.   
    4. export default class DisplayAnImage extends Component {  
    5.     render() {  
    6.         return (  
    7.             <ImageBackground source = {{uri:’https://www.javatpoint.com/tutorial/react-native/images/react-native-tutorial.png’}}  
    8.                              style={{width: ‘100%’, height: ‘100%’}}>  
    9.                <Image source={require(‘./favicon.png’)} />  
    10.                 <Image  
    11.                     source={require(‘/ReactNative/MyReactNativeApp/img/favicon.png’)}  
    12.                 />  
    13.   
    14.                 <Image  
    15.                     source={require(‘MyReactNativeApp/img/favicon.png’)}  
    16.                 />  
    17.                 <Image source={{uri: ‘asset:/images/favicon.png’}} style={{width: 60, height: 60}} />  
    18.                 <Image source = {{uri:’https://www.javatpoint.com/images/logo/jtp_logo.png’}}  
    19.                        style = {{ width: ‘80%’, height: 70 }}  
    20.                 />  
    21.                 <Image  
    22.                     style={{width: 60, height: 60}}  
    23.                     source={{uri: ‘data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==’}}  
    24.                 />  
    25.   
    26.             </ImageBackground>  
    27.   
    28.         );  
    29.     }  
    30. }  
    31. // skip this line if using Create React Native App  
    32. AppRegistry.registerComponent(‘DisplayAnImage’, () => DisplayAnImage);  

    Output:

  • React Native Animation

    React Native Animations provide an extra effect and great user experience in the app. Animations convey physically believable motion in your interface.

    There are two types of complementary animation systems in React Native. These are:

    • Animated: The Animated API is used to interactive control the specific values. It focuses on declarative relationships between inputs and outputs. It has a start and stop methods to control the time-based animation execution.
    • LayoutAnimated: The LayoutAnimated is used to animate the global layout transactions.
    • import React, { Component } from ‘react’;  
    • import {StyleSheet, AppRegistry,Text, View,Animated,Easing} from ‘react-native’;  
    •   
    • export default class DisplayAnImage extends Component {  
    •     constructor () {  
    •         super()  
    •         this.spinValue = new Animated.Value(0)//declare spinValue as a new Animated.Value and pass 0 (zero) in it.  
    •     }  
    •     componentDidMount () {  
    •         this.spin()  
    •     }  
    •     //create a spin method and call it from componentDidMount  
    •     spin () {  
    •         this.spinValue.setValue(0) //set spinValue to 0 (zero)  
    •         Animated.timing(    //calling Animated.timing() method, it takes two arguments:  
    •             this.spinValue, // value  
    •             {           // and config object  
    •                 toValue: 1, //and setting spinValue to 1  
    •                 duration: 4000, //within 4000 milliseconds  
    •                 easing: Easing.linear  
    •             }  
    •         ).start(() => this.spin())  
    •     }  
    •     render () {  
    •         const spin = this.spinValue.interpolate({  
    •             inputRange: [0, 1],  
    •             outputRange: [‘0deg’, ‘360deg’]  
    •         })  
    •         return (  
    •             <View style={styles.container}>  
    •                 <Animated.Image  
    •                     style={{  
    •                         width: 227,  
    •                         height: 200,  
    •                         transform: [{rotate: spin}] }}  
    •                     source={require(‘MyReactNativeApp/img/react-logo.png’)}  
    •                 />  
    •             </View>  
    •         )  
    •     }  
    • }  
    • const styles = StyleSheet.create({  
    •     container: {  
    •         flex: 1,  
    •         justifyContent: ‘center’,  
    •         alignItems: ‘center’  
    •     }  
    • })  
    • // skip this line if you are using Create React Native App  
    •   
    • AppRegistry.registerComponent(‘DisplayAnImage’, () => DisplayAnImage);  
    • import React, { Component } from ‘react’;  
    • import {StyleSheet, AppRegistry,Text, View,Animated,Easing} from ‘react-native’;  
    •   
    • export default class DisplayAnImage extends Component {  
    •     constructor () {  
    •         super()  
    •         this.animatedValue = new Animated.Value(0)  
    •     }  
    •     componentDidMount () {  
    •         this.animate()  
    •     }//animate method is call from componentDidMount  
    •     animate () {  
    •         this.animatedValue.setValue(0)  
    •         Animated.timing(  
    •             this.animatedValue,  
    •             {  
    •                 toValue: 1,  
    •                 duration: 2000,  
    •                 easing: Easing.linear  
    •             }  
    •         ).start(() => this.animate())  
    •     }  
    •   
    •     render() {  
    •         const marginLeft = this.animatedValue.interpolate({  
    •             inputRange: [0, 1],  
    •             outputRange: [0, 300]  
    •         })  
    •         const opacity = this.animatedValue.interpolate({  
    •             inputRange: [0, 0.5, 1],  
    •             outputRange: [0, 1, 0]  
    •         })  
    •         const movingMargin = this.animatedValue.interpolate({  
    •             inputRange: [0, 0.5, 1],  
    •             outputRange: [0, 300, 0]  
    •         })  
    •         const textSize = this.animatedValue.interpolate({  
    •             inputRange: [0, 0.5, 1],  
    •             outputRange: [18, 32, 18]  
    •         })  
    •         const rotateX = this.animatedValue.interpolate({  
    •             inputRange: [0, 0.5, 1],  
    •             outputRange: [‘0deg’, ‘180deg’, ‘0deg’]  
    •         })  
    •   
    •   
    •         return (  
    •             <View style={styles.container}>  
    •                 <Animated.View //returns Animated.View  
    •                     style={{  
    •                         marginLeft,  
    •                         height: 30,  
    •                         width: 40,  
    •                         backgroundColor: ‘red’}} />  
    •                 <Animated.View  
    •                     style={{  
    •                         opacity,  
    •                         marginTop: 10,  
    •                         height: 30,  
    •                         width: 40,  
    •                         backgroundColor: ‘blue’}} />  
    •                 <Animated.View  
    •                     style={{  
    •                         marginLeft: movingMargin,  
    •                         marginTop: 10,  
    •                         height: 30,  
    •                         width: 40,  
    •                         backgroundColor: ‘orange’}} />  
    •                 <Animated.Text // returns Animated.Text  
    •                     style={{  
    •                         fontSize: textSize,  
    •                         marginTop: 10,  
    •                         color: ‘green’}} >  
    •                     Animated Text!  
    •                 </Animated.Text>  
    •                 <Animated.View   
    •                     style={{  
    •                         transform: [{rotateX}],  
    •                         marginTop: 50,  
    •                         height: 30,  
    •                         width: 40,  
    •                         backgroundColor: ‘black’}}>  
    •                     <Text style={{color: ‘white’}}>Hello from TransformX</Text>  
    •                 </Animated.View>  
    •             </View>  
    •         )  
    •     }  
    • }  
    • const styles = StyleSheet.create({  
    •     container: {  
    •         flex: 1,  
    •         paddingTop: 150  
    •     }  
    • })   
    • // skip this line if you are using Create React Native App  
    • AppRegistry.registerComponent(‘DisplayAnImage’, () => DisplayAnImage);  
    • UIManager.setLayoutAnimationEnabledExperimental &&  
    •   UIManager.setLayoutAnimationEnabledExperimental(true);  
    • import React from ‘react’;  
    • import {  
    •     NativeModules,  
    •     LayoutAnimation,  
    •     Text,  
    •     TouchableOpacity,  
    •     StyleSheet,  
    •     View,  
    • } from ‘react-native’;  
    •   
    • const { UIManager } = NativeModules;  
    •   
    • UIManager.setLayoutAnimationEnabledExperimental &&  
    • UIManager.setLayoutAnimationEnabledExperimental(true);  
    •   
    • export default class App extends React.Component {  
    •     state = {  
    •         w: 100,  
    •         h: 100,  
    •     };  
    •   
    •     _onPress = () => {  
    •         // Animate the update  
    •         LayoutAnimation.spring();  
    •         this.setState({w: this.state.w + 15, h: this.state.h + 15})  
    •     }  
    •   
    •     render() {  
    •         return (  
    •             <View style={styles.container}>  
    •                 <View style={[styles.box, {width: this.state.w, height: this.state.h}]} />  
    •                 <TouchableOpacity onPress={this._onPress}>  
    •                     <View style={styles.button}>  
    •                         <Text style={styles.buttonText}>Press me!</Text>  
    •                     </View>  
    •                 </TouchableOpacity>  
    •             </View>  
    •         );  
    •     }  
    • }  
    •   
    • const styles = StyleSheet.create({  
    •     container: {  
    •         flex: 1,  
    •         alignItems: ‘center’,  
    •         justifyContent: ‘center’,  
    •     },  
    •     box: {  
    •         width: 200,  
    •         height: 200,  
    •         backgroundColor: ‘blue’,  
    •     },  
    •     button: {  
    •         backgroundColor: ‘green’,  
    •         paddingHorizontal: 20,  
    •         paddingVertical: 15,  
    •         marginTop: 15,  
    •     },  
    •     buttonText: {  
    •         color: ‘#fff’,  
    •         fontWeight: ‘bold’,  
    •     },  
    • });  
  • React Native ProgressBar With Animated

    React Native ProgressBar with Animated Example

    To create an animated progessbar we need to import theAnimated class. Add Animated.View and Animated.Text component inside View. Initialize a variable progress status to 0 and call the onAnimate() method. This method will invoked when the screen will completely loaded (componentDidMount() calls). Add a listener on onAnimate() method which updates the progress status.

    App.js

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text, View, Animated} from ‘react-native’;  
    3.   
    4. export default class App extends Component {  
    5.     state={  
    6.         progressStatus: 0,  
    7.     }  
    8.     anim = new Animated.Value(0);  
    9.     componentDidMount(){  
    10.         this.onAnimate();  
    11.     }  
    12.     onAnimate = () =>{  
    13.         this.anim.addListener(({value})=> {  
    14.             this.setState({progressStatus: parseInt(value,10)});  
    15.         });  
    16.         Animated.timing(this.anim,{  
    17.              toValue: 100,  
    18.              duration: 50000,  
    19.         }).start();  
    20.     }  
    21.   render() {  
    22.     return (  
    23.       <View style={styles.container}>  
    24.             <Animated.View  
    25.                 style={[  
    26.                     styles.inner,{width: this.state.progressStatus +”%”},  
    27.                 ]}  
    28.             />  
    29.             <Animated.Text style={styles.label}>  
    30.                     {this.state.progressStatus }%  
    31.             </Animated.Text>  
    32.       </View>  
    33.     );  
    34.   }  
    35. }  
    36. const styles = StyleSheet.create({  
    37.     container: {  
    38.     width: “100%”,  
    39.     height: 40,  
    40.     padding: 3,  
    41.     borderColor: “#FAA”,  
    42.     borderWidth: 3,  
    43.     borderRadius: 30,  
    44.     marginTop: 200,  
    45.     justifyContent: “center”,  
    46.   },  
    47.   inner:{  
    48.     width: “100%”,  
    49.     height: 30,  
    50.     borderRadius: 15,  
    51.     backgroundColor:”green”,  
    52.   },  
    53.   label:{  
    54.     fontSize:23,  
    55.     color: “black”,  
    56.     position: “absolute”,  
    57.     zIndex: 1,  
    58.     alignSelf: “center”,  
    59.   }  
    60. });  

    The progress status of progress bar is updated in the interval of per 0.5 second (50000 microseconds). At the same time the width of progress bar is determined by progress status, and its status is set into Animated.Text component.

    Output:

    React Native ProgressBar With Animated
    React Native ProgressBar With Animated
  • React Native ProgressBarAndroid

    The ProgressBarAndroid component of React Native is used to indicate the progress status of some activity or app loading something. ProgressBarAndroid component works only on Android platform. To use the progress bar in iOS platform, a ProgressViewIOS component is used.

    Props of ProgressBarAndroid

    PropsTypeRequiredDescription
    animatingboolnoIt is used to show or hide the progress bar. Its default value is true to show, (false to hide).
    colorcolornoIt sets the color of progress bar.
    indeterminateindeterminateTypenoIt shows the intermediate progress status of progress bar. It can only be false if the styleAtte of progress bar is Horizontal.
    progressnumbernoIt is a progress value between 0 and 1.
    styleAttrenumnoIt sets the style of progress bar. There are various style of progress bar in React Native such as Horizontal, Normal (default), Small, Large, Inverse, SmallInverse, and LargeInverse.
    testIDstringnoIt is used to locate this view in end-to-end tests.

    React Native ProgressBarAndroid Example

    In this example, we will implement horizontal ProgressBarAndroid and perform action on TouchableOpacity component. The progress status will display in Text component up to 3 digits only.

    1. import React, { Component } from ‘react’;  
    2. import { Platform, StyleSheet, View, Text, TouchableOpacity, ProgressBarAndroid, ProgressViewIOS } from ‘react-native’;  
    3. export default class MyApp extends Component<{}>{  
    4.   constructor()  {  
    5.     super();  
    6.     this.state = {  
    7.       progressStatus: 0,  
    8.     }  
    9.   }  
    10.   
    11.   start_Progress = () => {  
    12.     this.value = setInterval( () => {  
    13.       if(this.state.progressStatus <= 1){  
    14.         this.setState({progressStatus: this.state.progressStatus+ .01})  
    15.       }  
    16.     }, 100 );  
    17.   }  
    18.   
    19.   stop_Progress = () =>{  
    20.    clearInterval(this.value);  
    21.   }  
    22.   
    23.   clear_Progress =()=>{  
    24.     this.setState({progressStatus : 0.0})  
    25.   }  
    26.   
    27.   render()  
    28.   {  
    29.     return(  
    30.       <View style = { styles.MainContainer }>  
    31.         <Text style = {{fontSize: 20, color: ‘#000’}}> Progress Value: { parseFloat((this.state.progressStatus * 100).toFixed(3))} %</Text>{  
    32.             ( Platform.OS === ‘android’ )  
    33.             ?  
    34.               ( <ProgressBarAndroid styleAttr = “Horizontal” progress = { this.state.progressStatus } indeterminate = { false } /> )  
    35.             :  
    36.               ( <ProgressViewIOS progress = { this.state.progressStatus } /> )  
    37.         }  
    38.         <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.start_Progress }>  
    39.           <Text style = { styles.TextStyle }> Start Progress </Text>  
    40.         </TouchableOpacity>  
    41.         <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.stop_Progress }>  
    42.           <Text style = { styles.TextStyle }> Stop Progress </Text>  
    43.         </TouchableOpacity>  
    44.         <TouchableOpacity activeOpacity = { 1 } style = { styles.button } onPress = { this.clear_Progress }>  
    45.           <Text style = { styles.TextStyle }> Reset Progress </Text>  
    46.         </TouchableOpacity>  
    47.       </View>  
    48.     );  
    49.   }  
    50. }  
    51.   
    52. const styles = StyleSheet.create(  
    53. {  
    54.   MainContainer:  
    55.   {  
    56.     flex: 1,  
    57.     justifyContent: ‘center’,  
    58.     paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0,  
    59.     margin: 20  
    60.   },  
    61.   
    62.   button: {  
    63.   width: ‘100%’,  
    64.   backgroundColor: ‘#00BCD4’,  
    65.   borderRadius:5,  
    66.   padding: 10,  
    67.   marginTop: 10,  
    68.   
    69. },  
    70.   
    71. TextStyle:{  
    72.     color:’#fff’,  
    73.     textAlign:’center’,  
    74.     fontWeight: ‘bold’,  
    75. }  
    76. });  

    Output:

    React Native ProgressBarAndroid
    React Native ProgressBarAndroid
  • React Native WebView

    React Native WebView is a component which is used to load web content or web page. The WebView component is imports form core react-native library. Now, the WebView is replaced from the built-in core react-native, and placed in react-native-webview library.

    Note: The React Native WebView recommended to import react-native-webview or react-native-community library.

    Props of WebView

    sourceinjectJavaScriptinjectedJavaScriptonError
    onLoadonLoadEndonLoadStartonMessage
    originWhitelistrenderErrorstyleuserAgent
    htmlurlgeolocationEnabledscrollEnabled
    contentInsetbouncesallowFileAccessnativeConfig

    Types of WebView contents:

    Display HTML code as a string: The HTML string code is passed into html prop inside source property.

    1. <WebView  
    2.     source={{html: ‘<h1>Hello javaTpoint</h1>’}}  
    3. />  

    Display the internal web page: Create an internal web page inside a directory and pass its full path in source property.

    1. <WebView  
    2.     source={require(“./resources/index.html”)}  
    3. />  

    Display the remote web page: A remote web page is loaded using uri tag with source property.

    1. <WebView  
    2.     source = {{ uri:’https://www.javatpoint.com’ }}  
    3. />  

    React Native WebView Example 1

    in this example, we will load the web page by passing its URL in source prop of WebView component.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {  
    3.     View,WebView,StyleSheet,AppRegistry  
    4. } from ‘react-native’  
    5.   
    6. export default class ActivityIndicatorDemo extends Component {  
    7.     render() {  
    8.         return (  
    9.         <View style = {styles.container}>  
    10.             <WebView  
    11.                 source = {{ uri:’https://www.javatpoint.com’ }}  
    12.             />  
    13.         </View>  
    14.         )  
    15.     }  
    16. }  
    17. const styles = StyleSheet.create({  
    18.     container: {  
    19.         flex: 1,  
    20.     }  
    21. })  
    22.   
    23. AppRegistry.registerComponent(‘App’, () => ActivityIndicatorDemo)  
    React Native WebView

    React Native WebView Example 2

    In this example, we will import WebView from react-native-webview.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {  
    3.     View,StyleSheet,AppRegistry  
    4. } from ‘react-native’  
    5. import {WebView} from ‘react-native-webview’  
    6.   
    7. export default class ActivityIndicatorDemo extends Component {  
    8.     render() {  
    9.         return (  
    10.             <View style = {styles.container}>  
    11.                 {/*<WebView 
    12.                     source={{html: ‘<h1>Hello javaTpoint</h1>’}} 
    13.                 />*/}  
    14.              {/*   <WebView 
    15.                     source={require(“./resources/index.html”)} 
    16.                 />*/}  
    17.                 <WebView  
    18.                     source = {{ uri:’https://www.javatpoint.com’ }}  
    19.                 />  
    20.             </View>  
    21.         )  
    22.     }  
    23. }  
    24. const styles = StyleSheet.create({  
    25.     container: {  
    26.         flex: 1,  
    27.     }  
    28. })  
    29.   
    30. AppRegistry.registerComponent(‘App’, () => ActivityIndicatorDemo)  

    Output:

    React Native WebView

    Note: if you got an error message of module react-native-webview does not exist in the module map react native. Then make sure you install the below libraries:

    • npm install -g yarn
    • yarn add react-native-webview
    • react-native link react-native-webview
  • React Native Switch

    React Native Switch is a Boolean control component which sets its value to true or false. It has an onValueChange callback method that updates its value prop. If the value prop is not changed, the Switch component continues supplied the value prop instead of the expected result of any user actions.

    Props of Switch

    PropsDescription
    disabledIt is a Boolean property, if it is set to true then it cannot be toggled to switch. Its default value is false.
    trackColorIt is used to customize the color for switch track.
    ios_backgroundColorIt set the custom background color in iOS. The background can be visible either when the switch value is disabled or when the switch is false.
    onValueChangeIt invoked when the switch value is changed.
    testIDIt is used to locate this view in end-to-end tests.
    thumbColorIt colors the foreground switch grip. When it is set to iOS, the switch grip will lose its drop shadow.
    tintColorIt sets the border color on iOS and background color on Android when the switch is turned off. This property is deprecated; use trackColor at the place of it.
    valueIt is the value of switch. When it is set to true, it turns on. The default value is false.

    React Native Switch Example

    In this example, we initialy set the Switch value to false and display a Text with ‘off’. When the value of Switch change to true by calling onValueChange the Text component is reset to ‘on’.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {StyleSheet, Switch, View, Text} from ‘react-native’  
    3.   
    4. export default class SwitchExample extends Component {  
    5.     state = {  
    6.         switchValue: false  
    7.     };  
    8.   
    9.     render() {  
    10.         return (  
    11.             <View style={styles.container}>  
    12.                 <Text style={styles.textStyle}>Switch Example</Text>  
    13.                 <Text style={styles.textStyle}>{this.state.switchValue ? ‘on’ :’off’}</Text>  
    14.                 <Switch  
    15.                     value={this.state.switchValue}  
    16.                     onValueChange ={(switchValue)=>this.setState({switchValue})}/>  
    17.             </View>  
    18.         );  
    19.     }  
    20. }  
    21. const styles = StyleSheet.create ({  
    22.      container: {  
    23.          flex: 1,  
    24.          alignItems: ‘center’,  
    25.          justifyContent: ‘center’,  
    26.      },  
    27.     textStyle:{  
    28.         margin: 24,  
    29.         fontSize: 25,  
    30.         fontWeight: ‘bold’,  
    31.         textAlign: ‘center’,  
    32.         color: ‘#344953’  
    33.     }  
    34. })  

    Output:

    React Native Switch
    React Native Switch