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.