Author: saqibkhan

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

    The FlatList component displays the similar structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time. The FlatList shows only those renders elements which are currently displaying on the screen, not all the elements of the list at once.

    The FlatList component takes two required props: data and renderItem.

    The data is the source of elements for the list, and renderItem takes one item from the source and returns a formatted component to render.

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

    React Native FlatList Example

    In this example, we provide hardcoded elements to data prop. Each element in the data props is rendered as a Text component.

    The ItemSeparatorComponent prop of FlatList is used to implement the separator between the elements of the list. To perform the click event on list items, we use onPress prop to Text.

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, FlatList,  
    3.     StyleSheet, Text, View,Alert } from ‘react-native’;  
    4.   
    5. export default class FlatListBasics extends Component {  
    6.   
    7.     renderSeparator = () => {  
    8.         return (  
    9.             <View  
    10.                 style={{  
    11.                     height: 1,  
    12.                     width: “100%”,  
    13.                     backgroundColor: “#000”,  
    14.                 }}  
    15.             />  
    16.         );  
    17.     };  
    18.     //handling onPress action  
    19.     getListViewItem = (item) => {  
    20.         Alert.alert(item.key);  
    21.     }  
    22.   
    23.     render() {  
    24.         return (  
    25.             <View style={styles.container}>  
    26.                 <FlatList  
    27.                     data={[  
    28.                         {key: ‘Android’},{key: ‘iOS’}, {key: ‘Java’},{key: ‘Swift’},  
    29.                         {key: ‘Php’},{key: ‘Hadoop’},{key: ‘Sap’},  
    30.                         {key: ‘Python’},{key: ‘Ajax’}, {key: ‘C++’},  
    31.                         {key: ‘Ruby’},{key: ‘Rails’},{key: ‘.Net’},  
    32.                         {key: ‘Perl’},{key: ‘Sap’},{key: ‘Python’},  
    33.                         {key: ‘Ajax’}, {key: ‘C++’},{key: ‘Ruby’},  
    34.                         {key: ‘Rails’},{key: ‘.Net’},{key: ‘Perl’}  
    35.                     ]}  
    36.                     renderItem={({item}) =>  
    37.                         <Text style={styles.item}  
    38.                               onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}  
    39.                     ItemSeparatorComponent={this.renderSeparator}  
    40.                 />  
    41.             </View>  
    42.         );  
    43.     }  
    44. }  
    45.   
    46. const styles = StyleSheet.create({  
    47.     container: {  
    48.         flex: 1,  
    49.     },  
    50.     item: {  
    51.         padding: 10,  
    52.         fontSize: 18,  
    53.         height: 44,  
    54.     },  
    55. })  
    56.   
    57.   
    58. AppRegistry.registerComponent(‘AwesomeProject’, () => FlatListBasics);  

    Output:

    React Native FlatList
    React Native FlatList
  • React Native ListView

    React Native ListView is a view component which contains the list of items and displays in a vertical scrollable list. The minimum API to create list view is ListView.DataSource. It populates a simple array of data blobs, and instantiate a ListView component with data source and a renderRow callback. The renderRow takes a blob from data array and returns a renderable component.

    Note: The ListView component has deprecated. To implement the list component use new list components FlatList or SectionList.

    React Native ListView Example 1

    Let’s create an example of ListView component. In this example, we create a data source, and fill it with an array of data blobs. Create a ListView component using that array as its data source, and pass it in its renderRow callback. The renderRow is a function which returns a component which renders the row.

    1. import React, { Component } from ‘react’  
    2. import { Text, ListView, StyleSheet } from ‘react-native’  
    3.   
    4. export default class MyListComponent extends Component {  
    5.     constructor() {  
    6.         super();  
    7.         const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
    8.         this.state = {  
    9.             dataSource: ds.cloneWithRows([‘Android’,’iOS’, ‘Java’,’Php’, ‘Hadoop’,  
    10.                 ‘Sap’, ‘Python’,’Ajax’, ‘C++’,  
    11.                 ‘Ruby’, ‘Rails’,’.Net’, ‘Perl’]),  
    12.         };  
    13.     }  
    14.   
    15.     render() {  
    16.         return (  
    17.             <ListView  
    18.                 dataSource={this.state.dataSource}  
    19.                 renderRow={  
    20.                     (rowData) =>  
    21.                         <Text style={{fontSize: 20}}>{rowData}</Text>}  
    22.             />  
    23.         );  
    24.     }  
    25. }  

    Output:

    React Native ListView

    In the above code, we create an instance of ListViewDataSource in the constructor. The ListViewDataSource is a parameter and accept an argument which contain any of these four:

    • getRowData(dataBlob, sectionID, rowID)
    • getSectionHeaderData(dataBlob, sectionID)
    • rowHasChanged(previousRowData, nextRowData)
    • sectionHeaderHasChanged(previousSectionData, nextSectionData)

    Add separation and perform action on ListView items

    Separation is added to provide a separate block and for better display of list items. The props renderSeparator is used to add separator among the items (data) of ListView.

    Implement onPress props over Text to perform an action on clicking the list items. Here, we generate an alert message and display the list items on which a user click.

    1. import React from ‘react’;  
    2. import { View, ListView, StyleSheet, Text,Alert} from ‘react-native’;  
    3.   
    4. class ListViewDemo extends React.Component {  
    5.     constructor(props) {  
    6.         super(props);  
    7.   
    8.         const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
    9.         this.state = {  
    10.             dataSource: ds.cloneWithRows([ “Android”,  
    11.                 “iOS”,”Java”,”Swift”,  
    12.                 “Php”,”Hadoop”,”Sap”,  
    13.                 “Python”,”Ajax”, “C++”,  
    14.                 “Ruby”, “Rails”,”.Net”,  
    15.                 “Perl”,  
    16.             ])  
    17.         };  
    18.     }  
    19.     //handling onPress action  
    20.     getListViewItem = (rowData) => {  
    21.         Alert.alert(rowData);  
    22.     }  
    23.     render() {  
    24.         return (  
    25.                 <ListView  
    26.                     style={styles.container}  
    27.                     dataSource={this.state.dataSource}  
    28.                     renderRow={(rowData) =>  
    29.                        <Text style={styles.rowViewContainer}  
    30.                              onPress={this.getListViewItem.bind(this, rowData)}>{rowData}  
    31.                        </Text>  
    32.                     }  
    33.                     renderSeparator={(sectionId, rowId) =>  
    34.                         <View key={rowId} style={styles.separator} />}//adding separation  
    35.                 />  
    36.         );  
    37.     }  
    38. }  
    39.   
    40. const styles = StyleSheet.create({  
    41.     container: {  
    42.         flex: 1,  
    43.         backgroundColor: “#e5e5e5”  
    44.     },  
    45.     separator: {  
    46.         height: 0.5, width: “100%”, backgroundColor: “#000”  
    47.     },  
    48.     rowViewContainer: {  
    49.         flex: 1,  
    50.         paddingRight: 15,  
    51.         paddingTop: 13,  
    52.         paddingBottom: 13,  
    53.         borderBottomWidth: 0.5,  
    54.         borderColor: ‘#c9c9c9’,  
    55.         flexDirection: ‘row’,  
    56.         alignItems: ‘center’,  
    57.         fontSize: 20,  
    58.         marginLeft: 10,  
    59.     },  
    60. });  
    61.   
    62. export default ListViewDemo;  

    Output:

    React Native ListView
    React Native ListView
  • React Native ScrollView

    The ScrollView is a generic scrollable container, which scrolls multiple child components and views inside it. In the ScrollView, we can scroll the components in both direction vertically and horizontally. By default, the ScrollView container scrolls its components and views in vertical. To scroll its components in horizontal, it uses the props horizontal: true (default, horizontal: false).

    Props of ScrollView

    alwaysBounceVerticalonScrollhorizontal
    contentContainerStylescrollEnabledbouncesZoomzoomScale
    onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
    onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
    onScrollEndDragcenterContentcontentInsetrefreshControl
    pagingEnabledscrollsToTopsnapToAlignmentshowsHorizontalScrollIndicator
    snapToStartsnapToEndindicatorStyleshowsHorizontalScrollIndicator

    React Native ScrollView Example

    In this example, we create a vertical ScrollView using Text and Button components.

    App.js

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, ScrollView, Image, Text, Button, StyleSheet } from ‘react-native’;  
    3.   
    4. export default class ScrolledViewExample extends Component {  
    5.     onPressButton() {  
    6.         alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <ScrollView >  
    12.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    13.                 <Button title={‘Button 1’} onPress={this.onPressButton} />  
    14.                 <Text style={{fontSize:20}}>React Native Example of ScrollView</Text>  
    15.                 <Button title={‘Button 2’} onPress={this.onPressButton}/>  
    16.                 <Text style={{fontSize:20}}>React Native ScrollView Example</Text>  
    17.                 <Button title={‘Button 3’} onPress={this.onPressButton}/>  
    18.                 <Text style={{fontSize:20}}>If you like</Text>  
    19.                 <Button title={‘Button 4’} onPress={this.onPressButton}/>  
    20.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    21.                 <Button title={‘Button 5’} onPress={this.onPressButton}/>  
    22.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    23.                 <Button title={‘Button 6’} onPress={this.onPressButton}/>  
    24.                 <Text style={{fontSize:20}}>What’s the best</Text>  
    25.                 <Button title={‘Button 7’} onPress={this.onPressButton}/>  
    26.                 <Text style={{fontSize:20}}>What’s the best</Text>  
    27.                 <Button title={‘Button 8’} onPress={this.onPressButton}/>  
    28.                 <Text style={{fontSize:20}}>Framework around?</Text>  
    29.                 <Button title={‘Button 9’} onPress={this.onPressButton}/>  
    30.                 <Text style={{fontSize:20}}>Framework around?</Text>  
    31.                 <Button title={‘Button 10’} onPress={this.onPressButton}/>  
    32.                 <Text style={{fontSize:20}}>React Native</Text>  
    33.                 <Button title={‘Button 11’} onPress={this.onPressButton}/>  
    34.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    35.                 <Button title={‘Button 12’} onPress={this.onPressButton} />  
    36.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    37.                 <Button title={‘Button 13’} onPress={this.onPressButton}/>  
    38.                 <Text style={{fontSize:20}}>If you like</Text>  
    39.                 <Button title={‘Button 14’} onPress={this.onPressButton}/>  
    40.                 <Text style={{fontSize:20}}>If you like</Text>  
    41.                 <Button title={‘Button 15’} onPress={this.onPressButton}/>  
    42.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    43.                 <Button title={‘Button 16’} onPress={this.onPressButton}/>  
    44.             </ScrollView>  
    45.         );  
    46.     }  
    47. }  
    48. // skip this line if you are using Create React Native App  
    49. AppRegistry.registerComponent(‘AwesomeProject’, () => ScrolledViewExample);  

    Output:

    React Native ScrollView
    React Native ScrollView

    React Native Horizontal ScrollView Example

    The horizontal ScrollView scrolls the components and views from left to right. It will be implemented by setting the props horizontal to true (horizontal={true}).

    App.js

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, ScrollView, View, Image, Text, Button, StyleSheet } from ‘react-native’;  
    3.   
    4. export default class ScrolledViewExample extends Component {  
    5.     onPressButton() {  
    6.         alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <ScrollView  horizontal={true} style={styles.container}>  
    12.                 <Text style={{fontSize:22, padding: 10}}>Horizontal ScrollView</Text>  
    13.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    14.                     <Button  
    15.                         onPress={this.onPressButton}  
    16.                         title=”Button 1″  
    17.                         color=”#FF3D00″  
    18.                     />  
    19.                 </View>  
    20.                 <Text style={{fontSize:22, padding: 10}}>javatpoint</Text>  
    21.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    22.                     <Button  
    23.                         onPress={this.onPressButton}  
    24.                         title=”Button 2″  
    25.                         color=”#3D00FF”  
    26.                     />  
    27.                 </View>  
    28.                 <Text style={{fontSize:22, padding: 10}}>React Native ScrollView Example</Text>  
    29.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    30.                     <Button  
    31.                         onPress={this.onPressButton}  
    32.                         title=”Button 3″  
    33.                         color=”#FFFF3D”  
    34.                     />  
    35.                 </View>  
    36.                 <Text style={{fontSize:22, padding: 10}}>If you like</Text>  
    37.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    38.                     <Button  
    39.                         onPress={this.onPressButton}  
    40.                         title=”Button 4″  
    41.                         color=”#FF3DFF”  
    42.                     />  
    43.                 </View>  
    44.                 <Text style={{fontSize:22, padding: 10}}>Scrolling horizontal</Text>  
    45.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    46.                     <Button  
    47.                         onPress={this.onPressButton}  
    48.                         title=”Button 5″  
    49.                         color=”#3DFF00″  
    50.                     />  
    51.                 </View>  
    52.             </ScrollView>  
    53.         );  
    54.     }  
    55. }  
    56. const styles = StyleSheet.create({  
    57.     container:{  
    58.         flex: 1,  
    59.     },  
    60. /*    buttonStyle:{ 
    61.         height: 50, 
    62.         width: 70, 
    63.     }*/  
    64. })  
    65. // skip this line if you are using Create React Native App  
    66. AppRegistry.registerComponent(‘AwesomeProject’, () => ScrolledViewExample);  

    Output:

    React Native ScrollView
    React Native ScrollView
  • Positioning Element with Flex

    In the previous article Layout and Flexbox, we discuss about the Flexbox and its properties. In this tutorial, we will set the position of elements with Flex.

    Example 1

    Create a View component and place two elements TextInput and Button. The View component with flex property (1) occupy full space of device. The elements TextInput and Button are set in default flex axis (as column).

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, TextInput, View , Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <TextInput  
    24.                         placeholder=”An awesome place”  
    25.                         onChangeText={this.placeNameChangedHandler}  
    26.                         style={styles.placeInput}  
    27.                 />  
    28.                 <Button  
    29.                         title=”Button”  
    30.                         onPress={this.placeSubmitHandler}  
    31.                 />  
    32.             </View>  
    33.         );  
    34.     }  
    35. }  
    36.   
    37. const styles = StyleSheet.create({  
    38.     container: {  
    39.         flex: 1,  
    40.         padding: 26,  
    41.         backgroundColor: “#fff”,  
    42.         justifyContent: “flex-start”  
    43.     }  
    44. });  

    Output:

    React Native Positioning Element with Flex

    Example 2

    In this example, we will place the Button right to TextInput element. Add a child View component inside parent View with flex: 1 and flexDirtection : “row”. Setting flex: 1 for inner View occupies whole space from top to bottom and left to right. The flexDirtection: “row” set the elements in row-wise inside the inner View component.

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, View, TextInput, Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <View style={styles.innerContainer}>  
    24.                     <TextInput  
    25.                             placeholder=”An awesome place”  
    26.                             onChangeText={this.placeNameChangedHandler}  
    27.                     />  
    28.                     <Button  
    29.                             title=”Button”  
    30.                             onPress={this.placeSubmitHandler}  
    31.                     />  
    32.                 </View>  
    33.             </View>  
    34.         );  
    35.     }  
    36. }  
    37.   
    38. const styles = StyleSheet.create({  
    39.     container: {  
    40.         flex: 1,  
    41.         padding: 26,  
    42.         backgroundColor: “#fff”,  
    43.         justifyContent: “flex-start”  
    44.     },  
    45.     innerContainer:{  
    46.         flex: 1,  
    47.         flexDirection: “row”  
    48.     }  
    49. });  

    Output:

    React Native Positioning Element with Flex

    The flex: 1 for inner View occupy full space which does not look good as the TextInput and Button occupy all space from top to bottom.

    Example 3

    In this example, we remove flex property of inner View and add width: 100%. Removing flex form inner View set the default dimension of elements. Setting width :”100%” for inner View occupy full width and default height of elements.

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, View, TextInput, Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <View style={styles.innerContainer}>  
    24.                     <TextInput  
    25.                             placeholder=”An awesome place”  
    26.                             onChangeText={this.placeNameChangedHandler}  
    27.                             style={styles.textStyle}  
    28.                     />  
    29.                     <Button  
    30.                             title=”Button”  
    31.                             onPress={this.placeSubmitHandler}  
    32.                     />  
    33.                 </View>  
    34.             </View>  
    35.         );  
    36.     }  
    37. }  
    38.   
    39. const styles = StyleSheet.create({  
    40.     container: {  
    41.         flex: 1,  
    42.         padding: 26,  
    43.         backgroundColor: “#fff”,  
    44.         justifyContent: “flex-start”  
    45.     },  
    46.     innerContainer:{  
    47.        // flex: 1,  
    48.         width: “100%”,  
    49.         flexDirection: “row”,  
    50.         justifyContent: “space-between”,  
    51.         alignItems: “center”  
    52.     },  
    53.     textStyle:{  
    54.         width: “70%”,  
    55.         backgroundColor: “gray”,  
    56.     },  
    57.     buttonStyle:{  
    58.         width: “30%”,  
    59.     }  
    60. });  

    Output:

    React Native Positioning Element with Flex