How to use Map Function in React Native
The map function is used to show a list of elements from an array. Properly saying, The map() method creates a new array with the results of calling a provided function on every element in the calling array.
The Map method is commonly used in JavaScript, as you can see in the example given below:
var array = [1, 2, 3, 4];
const map = array.map(element => element * 2);
console.log(map);
// expected output: Array [2, 4, 6, 8]
We can use the map method in React Native easily, especially showing items as lists from an array. See the example code given below where a list is shown using the map function.
import React from 'react';
import {View, Text} from 'react-native';
const Home = () => {
const array = [
{
key: '1',
title: 'example title 1',
subtitle: 'example subtitle 1',
},
{
key: '2',
title: 'example title 2',
subtitle: 'example subtitle 2',
},
{
key: '3',
title: 'example title 3',
subtitle: 'example subtitle 3',
},
];
const list = () => {
return array.map(element => {
return (
<View key={element.key} style={{margin: 10}}>
<Text>{element.title}</Text>
<Text>{element.subtitle}</Text>
</View>
);
});
};
return <View>{list()}</View>;
};
export default Home;
The output will be as given in the screenshot below.
That’s how you use the map function in react native.
didn’t you get the key error?