How to use Map Function in React Native

Last Updated on December 10, 2020.

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

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. In the following react native example, I have declared an array in the state and showed the items as text using the map function. Following is how you use the map function in class-based components.

import React, {Component} from 'react';
import {Text, View} from 'react-native';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      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',
        },
      ],
    };
  }

  list = () => {
    return this.state.array.map((element) => {
      return (
        <View key={element.key} style={{margin: 10}}>
          <Text>{element.title}</Text>
          <Text>{element.subtitle}</Text>
        </View>
      );
    });
  };

  render() {
    return <View>{this.list()}</View>;
  }
}

You can use map function in functional component as given below.

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.

React Native Map Method

1 thought on “How to use Map Function in React Native”

Leave a Reply

%d bloggers like this: