React Native – ListView


React Native – ListView


”;


In this chapter, we will show you how to create a list in React Native. We will import List in our Home component and show it on screen.

App.js

import React from ''react''
import List from ''./List.js''

const App = () => {
   return (
      <List />
   )
}
export default App

To create a list, we will use the map() method. This will iterate over an array of items, and render each one.

List.js

import React, { Component } from ''react''
import { Text, View, TouchableOpacity, StyleSheet } from ''react-native''
   
class List extends Component {
   state = {
      names: [
         {
            id: 0,
            name: ''Ben'',
         },
         {
            id: 1,
            name: ''Susan'',
         },
         {
            id: 2,
            name: ''Robert'',
         },
         {
            id: 3,
            name: ''Mary'',
         }
      ]
   }
   alertItemName = (item) => {
      alert(item.name)
   }
   render() {
      return (
         <View>
            {
               this.state.names.map((item, index) => (
                  <TouchableOpacity
                     key = {item.id}
                     style = {styles.container}
                     onPress = {() => this.alertItemName(item)}>
                     <Text style = {styles.text}>
                        {item.name}
                     </Text>
                  </TouchableOpacity>
               ))
            }
         </View>
      )
   }
}
export default List

const styles = StyleSheet.create ({
   container: {
      padding: 10,
      marginTop: 3,
      backgroundColor: ''#d9f9b1'',
      alignItems: ''center'',
   },
   text: {
      color: ''#4f603c''
   }
})

When we run the app, we will see the list of names.

ListView

You can click on each item in the list to trigger an alert with the name.

React Native ListView

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *