Author: saqibkhan

  • 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
  • React Native StatusBar

    React Native StatusBar is a component which is used to decorate status bar of the app. It is used by importing the StatusBar component from the react-native library. We can use multiple StatusBar at the same time.

    1. <View>  
    2.    <StatusBar  
    3.      backgroundColor = “#b3e6ff”  
    4.      barStyle = “dark-content”   
    5.    />  
    6. </View>  

    1. <View>  
    2.   <StatusBar   
    3.      backgroundColor = “#b3e6ff”  
    4.      barStyle = “dark-content”   
    5.   />  
    6.   <View>  
    7.     <StatusBar   
    8.        hidden={route.statusBarHidden} />  
    9.   </View>  
    10. </View>  

    React Native StatusBar Props

    PropsDescription
    animatedA status bar is animated if its property is changed. It supports backgrondColor, hidden, and barStyle.
    barStyleIt sets the color of status bar text.
    hiddenIt is used to hide and show the status bar. By default, it is false. If hidden = {false} it is visible, if hidden = {true}, it hide the status bar.
    backgroundColorIt sets the background color of the status bar.
    translucentWhen it is set of true, the app is built under the status bar.
    showHideTransitionIt displays the transition effect when showing and hiding the status bar. The default is ‘fade’.
    networkActivityIndicatorVisibleIt checks the network activity indicator is visible or not. It supports in iOS.

    React Native StatusBar Methods

    setHiddensetBarStylesetBackgroundColor
    setNetworkActivityIndicatorVisiblesetTranslucent

    React Native StatusBar Example 1

    Let’s create a simple StatusBar example in which we change its background color.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {  
    3.     View,StyleSheet,AppRegistry,StatusBar  
    4. } from ‘react-native’  
    5.   
    6. export default class ActivityIndicatorDemo extends Component {  
    7.     render() {  
    8.         return (  
    9.             <View style = {styles.container}>  
    10.                 <StatusBar  
    11.                     backgroundColor = “#b3e6ff”  
    12.                     barStyle = “dark-content”   
    13.                     hidden = {false}    
    14.                     translucent = {true}  
    15.                 />  
    16.             </View>  
    17.         )  
    18.     }  
    19. }  
    20. const styles = StyleSheet.create({  
    21.     container: {  
    22.         flex: 1,  
    23.     }  
    24. })  
    25. AppRegistry.registerComponent(‘App’, () => ActivityIndicatorDemo)  

    Output:

    React Native StatusBar

    React Native StatusBar Example 2 (hiding status bar, full screen)

    In this example, we hide the StatusBar by using its property hidden = true. Hiding the StatusBar makes the display as full-screen.

    1. import React, { Component } from ‘react’  
    2. import {  
    3.     View,StyleSheet,AppRegistry,StatusBar  
    4. } from ‘react-native’  
    5.   
    6. export default class ActivityIndicatorDemo extends Component {  
    7.     render() {  
    8.         return (  
    9.             <View>  
    10.                 <StatusBar backgroundColor=”#b3e6ff” barStyle=”light-content” />  
    11.                 <View>  
    12.                     <StatusBar hidden={true} />  
    13.                 </View>  
    14.             </View>  
    15.         )  
    16.     }  
    17. }  
    18. const styles = StyleSheet.create({  
    19.     container: {  
    20.         flex: 1,  
    21.     }  
    22. })  
    23.   
    24. AppRegistry.registerComponent(‘App’, () => ActivityIndicatorDemo)  

    Output:

    React Native StatusBar
  • React Native Picker

    React Native Picker is component which is used to select an item from the multiple choices. This is the same as a Dropdown option. Picker is used when we need to provide an alternative to choose from multiple options.

    It is used by importing the Picker component from the react-native library.

    Props of Picker

    PropDescription
    onValueChange( itemValue, itemPosition)It is a callback prop and called when an item is selected. It takes two parameters (itemValue: the item (value) which is selected, itemPosition: the position (index) of a selected item).
    selectedValueReturns the selected value.
    styleIt is a picket style type.
    testIDIt is used to locate this view in end-to-end tests.
    enabledIt is a Boolean prop which makes picker disable when set to false. If it is set to false, the user cannot be able to make a selection.
    modeOn Android, it specifies how to display the selections items when the users click on the picker. It has the “dialog” and “dropdown” properties. The dialog is default mode and shows as a modal dialog. The dropdown displays the picker as dropdown anchor view.
    promptIt is used in Android with dialog mode as the title of the dialog.
    itemStyleIt styles each item of the picker labels.

    React Native Picker Example

    In this example, we create three label items in Picker component. When the item is selected from Picker, it calls the onValueChange callback and set the selected item in the picker. The index of item is read from itemPosition. The item’s position is displayed in a Text component.

    App.js

    1. import React, { Component } from ‘react’  
    2. import {StyleSheet,View, Text,Picker} from ‘react-native’  
    3.   
    4. export default class SwitchExample extends Component {  
    5.     state = {  
    6.         choosenIndex: 0  
    7.     };  
    8.   
    9.     render() {  
    10.         return (  
    11.             <View style={styles.container}>  
    12.                 <Text style={styles.textStyle}>Picker Example</Text>  
    13.                 <Picker style={styles.pickerStyle}  
    14.                         selectedValue={this.state.language}  
    15.                         onValueChange={(itemValue, itemPosition) =>  
    16.                             this.setState({language: itemValue, choosenIndex: itemPosition})}  
    17.                     >  
    18.                     <Picker.Item label=”Java” value=”java” />  
    19.                     <Picker.Item label=”JavaScript” value=”js” />  
    20.                     <Picker.Item label=”React Native” value=”rn” />  
    21.                 </Picker>  
    22.                 <Text style={styles.textStyle}> {“Index =”+this.state.choosenIndex}</Text>  
    23.             </View>  
    24.         );  
    25.     }  
    26. }  
    27. const styles = StyleSheet.create ({  
    28.      container: {  
    29.          flex: 1,  
    30.          alignItems: ‘center’,  
    31.          justifyContent: ‘center’,  
    32.      },  
    33.     textStyle:{  
    34.         margin: 24,  
    35.         fontSize: 25,  
    36.         fontWeight: ‘bold’,  
    37.         textAlign: ‘center’,  
    38.     },  
    39.     pickerStyle:{  
    40.         height: 150,  
    41.         width: “80%”,  
    42.         color: ‘#344953’,  
    43.         justifyContent: ‘center’,  
    44.     }  
    45. })  

    Output:

    React Native Picker
    React Native Picker
    React Native Picker
  • React Native ActivityIndicator

    ActivityIndicator is used to display a circular loading indicator.

    Props

    PropsDescription
    animatingOption to show the indicator (bydefault it is true) or hide it (false).
    sizeSet the size of indicator (‘small’,’large’, number). The default size is small. Number format support only in android.
    colorSet the foreground color of the spinner (default is gray).
    hidesWhenStoppedIt provides an option to show or hide the indicator when there is no animating (true by default).

    React Native ActivityIndicator Example

    In this example, the animating property set the activity indicator to true, and it is visible on the screen. When the component mounts, the animated activity indicator will be closed after six seconds using the closeActivityIndicator() method.

    1. import React, { Component } from ‘react’  
    2. import {  
    3.     ActivityIndicator,  
    4.     AppRegistry,  
    5.     StyleSheet,  
    6.     Text,  
    7.     View,  
    8. } from ‘react-native’  
    9.   
    10. export default class ActivityIndicatorDemo extends Component {  
    11.     state = { animating: true }  
    12.     closeActivityIndicator = () => setTimeout(() => this.setState({  
    13.         animating: false }), 6000)  
    14.     componentDidMount = () => this.closeActivityIndicator()  
    15.     render() {  
    16.         const animating = this.state.animating  
    17.         return (  
    18.             <View style={[styles.container, styles.horizontal]} >  
    19.                 <ActivityIndicator  animating = {animating} size=”large” color=”#ff0000″ />  
    20.                 <ActivityIndicator size=”small” color=”#44ff00″ />  
    21.                 <ActivityIndicator size=”large” color=”#rtwrw” />  
    22.             </View>  
    23.         )  
    24.     }  
    25. }  
    26.   
    27. const styles = StyleSheet.create({  
    28.     container: {  
    29.         flex: 1,  
    30.         justifyContent: ‘center’  
    31.     },  
    32.     horizontal: {  
    33.         flexDirection: ‘row’,  
    34.         justifyContent: ‘space-around’,  
    35.         padding: 10  
    36.     }  
    37. })  
    38.   
    39. AppRegistry.registerComponent(‘App’, () => ActivityIndicatorDemo)  

    Output:

    React Native ActivityIndicator
  • React Native Text Input

    TextInput is the fundamental component to input text. It has several props which configure the different features, such as onChangeText that takes a function and call it whenever the text changed. The onSubmitEditing prop takes a function, which is called when the text submitted.

    There are several things, which can be performed with text input, such as validating the text inside while user types.

    React Native TextInput Example 1

    In this example, we create a TextInput and perform an onChangeText action. At every text change, it calls the setState and checks the condition of a split. If the input text found ‘ ‘ space, it displays ‘?’ in the text. The text is placed in state as it is changed every time.

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, Text, TextInput, View } from ‘react-native’;  
    3.   
    4. export default class PizzaTranslator extends Component {  
    5.     constructor(props) {  
    6.         super(props);  
    7.         this.state = {text: ”};  
    8.     }  
    9.   
    10.     render() {  
    11.         return (  
    12.             <View style={{padding: 10}}>  
    13.                 <TextInput  
    14.                     style={{height: 40,backgroundColor: ‘azure’, fontSize: 20}}  
    15.                     placeholder=”Type here to translate!”  
    16.                     onChangeText={(text) => this.setState({text})}  
    17.                 />  
    18.                 <Text style={{padding: 100, fontSize: 50}}>  
    19.                     {this.state.text.split(‘ ‘).map((word) => word && ‘?’).join(‘ ‘)}  
    20.                 </Text>*  
    21.             </View>  
    22.         );  
    23.     }  
    24. }  

    Output

    React Native Text Input
    React Native Text Input

    TextInput properties

    allowFontScalingautoCapitalizeautoCorrectautoFocus
    blurOnSubmitcaretHiddenclearButtonModeclearTextOnFocus
    contextMenuHiddendataDetectorTypesdefaultValuedisableFullscreenUI
    editableenablesReturnKeyAutomaticallyinlineImageLeftinlineImagePadding
    keyboardAppearancekeyboardTypemaxLengthmultiline
    numberOfLinesonBluronChangeonChangeText
    onContentSizeChangeonEndEditingonFocusonKeyPress
    onLayoutonScrollonSelectionChangeonSubmitEditing
    placeholderplaceholderTextColorreturnKeyLabelreturnKeyType
    scrollEnabledsecureTextEntryselectionselectionColor
    selectionColorselectionStateselectTextOnFocusspellCheck
    textContentTypestyletextBreakStrategyunderlineColorAndroid

    The method .focus() and .blur() are exposed from the native element. These methods focus or blur the TextInput programmatically.

    Multiline TextInput

    The multiline props provide facility to input multiple lines of text. Some props of TextInput are only compatible with multiline, for example, multiline={true/false}. The property borderButtomColor will not work if multiline = false.

    React Native TextInput Example 2

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, View, TextInput } from ‘react-native’;  
    3.   
    4. class UselessTextInput extends Component {  
    5.     render() {  
    6.         return (  
    7.             <TextInput  
    8.                 {…this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below  
    9.                 editable = {true}  
    10.                 maxLength = {40}  
    11.             />  
    12.         );  
    13.     }  
    14. }  
    15. export default class UselessTextInputMultiline extends Component {  
    16.     constructor(props) {  
    17.         super(props);  
    18.         this.state = {  
    19.             text: ‘Useless Multiline Placeholder’,  
    20.         };  
    21.     }  
    22.   
    23.       
    24.     render() {  
    25.         return (  
    26.             <View style={{  
    27.                 backgroundColor: this.state.text,  
    28.                 borderBottomColor: ‘#000000’,  
    29.                 borderBottomWidth: 1,  
    30.                }}  
    31.             >  
    32.                 <UselessTextInput  
    33.                     multiline = {true}  
    34.                     numberOfLines = {10}  
    35.                     onChangeText={(text) => this.setState({text})}  
    36.                     value={this.state.text}  
    37.                     style={{fontSize: 20}}  
    38.                 />  
    39.             </View>  
    40.         );  
    41.     }  
    42. }  

    Output

    React Native Text Input
    React Native Text Input
  • React Native Touchables

    Touchable components provide the capability to capture the tapping functionality. The touchables component can be implemented as an alternative of basic button, if they are not look right for your app. Using these components, you build your own button. Tapping on these components, you can display the feedback.

    The touchables components do not provide any default styling, so you will need to do your style for presenting nicely in the app.

    Types of Touchable Components

    There are four touchable components provided by React Native. Selection of this component depends on the kind of feedback you want to provide:

    • TouchableHighlight
    • TouchableNativeFeedback
    • TouchableOpacity
    • TouchableWithoutFeedback.

    React Native TouchableHighlight

    The TouchableHighlight can be used where you would use a button or link on the web. The background of this component becomes dark on pressing it.

    Props

    PropsTypeRequiredPlatformDescription
    activeOpacitynumbernoDetermines the opacity of wrapped view when it is touched.
    onHideUnderlayfunctionnoCalls instantly after the underlay is hidden.
    onShowUnderlayfunctionnoCalls instantly after the underlay is shown.
    styleView.styleno
    underlayColorcolornoShow the underlay color when the touch is active.
    hasTVPreferredFocusboolnoiOSIt focuses TV preferred, work only for iOS.
    tvParallaxPropertiesobjectnoiOSIt is an object with properties which control the Apple TV parallax effects.

    React Native TouchableNativeFeedback

    The TouchableNativeFeedback makes a view to response properly on touch. This component works only for Android operating system. It uses native state drawable to display the touch feedback.

    It supports only a single View instance as a child node. It is implemented by replacing the View with another instance of RCTView node.

    Props

    PropsTypeRequiredDescription
    backgroundbackgroundPropTypenoIt determines the background drawable that is going to be displayed as feedback.
    useForegroundboolnoIt adds the ripple effect to the foreground of the view, instead of the background.

    React Native TouchableOpacity

    The TouchableOpacity wrapper is used to reduce the opacity of button. It allows background to be seen while the user press down. The opacity of button will be controlled by wrapping the children in an Animation.

    Props

    PropsTypeRequiredPlatformDescription
    activeOpacitynumbernoIt determines the opacity of wrapped view when it is touched.
    tvParallaxPropertiesobjectnoiOSIt is an object with property which is used to control the Apple TV parallax effects.
    hasTVPreferredFocusboolnoiOSIt focuses TV preferred, it works on Apple TV only.

    Methods

    MethodDescription
    setOpacityTo()It animates the touchable to a new opacity.

    React Native TouchableWithoutFeedback

    The TouchableWithoutFeedback is used when the user wants to handle the tap functionality but doesn’t want to display any feedback.

    Props

    PropsTypeRequiredDescription
    hitSlopobjectnoThis defines how far your touch can start away from the button.
    onAccessibilityTapfunctionnoIf accessible is set to true, the system invokes this function when the user performs accessibility tap gesture.
    accessibilityHintstringnoIt helps user to understand what will happen when they perform an action on the accessibility element.
    accessibilityLabelnodenoIt overrides the text, which is read by the screen reader when users interact with the element.
    delayLongPressnumbernoIt delays the onLongPress in milli-second calling onPressIn.

    Some time user presses a view and holds it for the set of time. This long press is handled by the function using onLongPress props of any of the above “Touchable” components.

    React Native Touchables Example

    1. import React, { Component } from ‘react’;  
    2. import { Alert,Platform,StyleSheet,Text,TouchableHighlight,TouchableOpacity,  
    3.     TouchableNativeFeedback,TouchableWithoutFeedback, View } from ‘react-native’;  
    4.   
    5. export default class Touchables extends Component {  
    6.     _onPressButton() {  
    7.         Alert.alert(‘You tapped the button!’)  
    8.     }  
    9.   
    10.     _onLongPressButton() {  
    11.         Alert.alert(‘You long-pressed the button!’)  
    12.     }  
    13.   
    14.   
    15.     render() {  
    16.         return (  
    17.             <View style={styles.container}>  
    18.                 <TouchableHighlight onPress={this._onPressButton} underlayColor=”white”>  
    19.                     <View style={styles.button}>  
    20.                         <Text style={styles.buttonText}>TouchableHighlight</Text>  
    21.                     </View>  
    22.                 </TouchableHighlight>  
    23.                 <TouchableOpacity onPress={this._onPressButton}>  
    24.                     <View style={styles.button}>  
    25.                         <Text style={styles.buttonText}>TouchableOpacity</Text>  
    26.                     </View>  
    27.                 </TouchableOpacity>  
    28.                 <TouchableNativeFeedback  
    29.                     onPress={this._onPressButton}  
    30.                     background={Platform.OS === ‘android’ ? TouchableNativeFeedback.SelectableBackground() : ”}>  
    31.                     <View style={styles.button}>  
    32.                         <Text style={styles.buttonText}>TouchableNativeFeedback</Text>  
    33.                     </View>  
    34.                 </TouchableNativeFeedback>  
    35.                 <TouchableWithoutFeedback  
    36.                     onPress={this._onPressButton}  
    37.                 >  
    38.                     <View style={styles.button}>  
    39.                         <Text style={styles.buttonText}>TouchableWithoutFeedback</Text>  
    40.                     </View>  
    41.                 </TouchableWithoutFeedback>  
    42.                 <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor=”white”>  
    43.                     <View style={styles.button}>  
    44.                         <Text style={styles.buttonText}>Touchable with Long Press</Text>  
    45.                     </View>  
    46.                 </TouchableHighlight>  
    47.             </View>  
    48.         );  
    49.     }  
    50. }  
    51.   
    52. const styles = StyleSheet.create({  
    53.     container: {  
    54.         paddingTop: 60,  
    55.         alignItems: ‘center’  
    56.     },  
    57.     button: {  
    58.         marginBottom: 30,  
    59.         width: 260,  
    60.         alignItems: ‘center’,  
    61.         backgroundColor: ‘#5ead97’  
    62.     },  
    63.     buttonText: {  
    64.         padding: 20,  
    65.         color: ‘white’,  
    66.         fontSize: 18  
    67.     }  
    68. });  

    Output:

    React Native Touchables
    React Native Touchables
    React Native Touchables
  • React Native SectionList

    The React Native SectionList component is a list view component which sets the list of data into broken logical section. The broken data can be implemented using its section header prop renderSectionHeader.

    To implement the SectionList component, we need to import SectionList from ‘react-native’ library.

    Props of SectionList

    sectionsrenderIteminitialNumToRenderkeyExtractor
    renderSectionHeaderrenderSectionFooteronRefreshinverted
    extraDataonEndReachedkeyExtractorlegacyImplementation
    onViewableItemsChangedrefreshingremoveClippedSubviewsListHeaderComponent
    SectionSeparatorComponentstickySectionHeadersEnabledonEndReachedThresholdListEmptyComponent

    React Native SectionList Example

    In this example, we create a SectionList with title and data. The sections prop is used to create the list of title and data values. The renderSectionHeader displays the header section of the list view.

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, SectionList, StyleSheet, Text, View } from ‘react-native’;  
    3.   
    4. export default class SectionListBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <SectionList  
    9.                     sections={[  
    10.                         {title: ‘A’, data: [‘ALTERED’,’ABBY’,’ACTION U.S.A.’,’AMUCK’,’ANGUISH’]},  
    11.                         {title: ‘B’, data: [‘BEST MEN’,’BEYOND JUSTICE’,’BLACK GUNN’,’BLOOD RANCH’,’BEASTIES’]},  
    12.                         {title: ‘C’, data: [‘CARTEL’, ‘CASTLE OF EVIL’, ‘CHANCE’, ‘COP GAME’, ‘CROSS FIRE’,]},  
    13.                     ]}  
    14.                     renderItem={({item}) => <Text style={styles.item}>{item}</Text>}  
    15.                     renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}  
    16.                     keyExtractor={(item, index) => index}  
    17.                 />  
    18.             </View>  
    19.         );  
    20.     }  
    21. }  
    22.   
    23. const styles = StyleSheet.create({  
    24.     container: {  
    25.         flex: 1,  
    26.         backgroundColor: “#5ead97”  
    27.     },  
    28.     sectionHeader: {  
    29.         paddingTop: 2,  
    30.         paddingLeft: 10,  
    31.         paddingRight: 10,  
    32.         paddingBottom: 2,  
    33.         fontSize: 22,  
    34.         fontWeight: ‘bold’,  
    35.         color: “#fff”,  
    36.         backgroundColor: ‘#8fb1aa’,  
    37.     },  
    38.     item: {  
    39.         padding: 10,  
    40.         fontSize: 18,  
    41.         height: 44,  
    42.     }  
    43. })  
    44.   
    45. // skip this line if using Create React Native App  
    46. AppRegistry.registerComponent(‘AwesomeProject’, () => SectionListBasics);  

    Output:

    React Native SectionList

    Adding Separator in SectionList

    ItemSeparatorComponent prop adds the Separator between the lists of data. Using this prop, call a renderSeparatormethod in which we add a View component as separator.

    1. renderSeparator = () => {  
    2.     return (  
    3.         <View  
    4.             style={{  
    5.                 height: 1,  
    6.                 width: “100%”,  
    7.                 backgroundColor: “#000”,  
    8.             }}  
    9.         />  
    10.     );  
    11. };  
    12.   
    13.   
    14. ItemSeparatorComponent={this.renderSeparator}  

    Performing action on SectionList items

    To perform an action on clicking (pressing) the list item, we use a onPress prop. The onPress prop and handle the event in another method getListViewItem.

    1. //handling onPress action  
    2.     getListViewItem = (item) => {  
    3.         alert(item);  
    4.     }  
    5.   
    6.   
    7. renderItem={({item}) => <Text style={styles.item}  
    8.   onPress={this.getListViewItem.bind(this, item)}>{item}</Text>}  

    Output:

    React Native SectionList
    React Native SectionList