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.

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

This comment has been removed by the author.
ReplyDeleteThe details that you mentioned regarding list view in react native is really great. I have gone through all the screenshots and the code also that you attached as sample and I believe that nothing could explain better than this.
ReplyDeleteI was searching for react native development company and got your blog.
Thanks sharing such a great blog.