Home > Mobile >  React native How to add Images with map()
React native How to add Images with map()

Time:03-15

import React from "react";
import { View, Text, StyleSheet, ScrollView, Image } from "react-native";

const Icons = [
  { name: "Food", uri: require("./images/Food.png") },
  { name: "Mart", uri: require("./images/mart.png") },
  { name: "Car",  uri: require("./images/car.png")  }
];

const IconSelection = Icons.map((icons) => (
  <View>
    <Image source={icons.uri} />
    <Text style={{ textAlign: "center" }}>{icons.name}</Text>
  </View>
));

const styles = StyleSheet.create({});

export default IconSelection;

IconSelection.js How do I add images inside my const Icons? Basically I want to create like a list of Icons using images and able to call them. Previously my method is basically handcode them but I found it is very messy. I think maps() could help me but I'm not really sure how to use it too. Thank you.

CodePudding user response:

IconSelectionis a reference to an array containing returned JSX.

Convert it into a functional component

import React from "react";
import { View, Text, StyleSheet, ScrollView, Image } from "react-native";

const Icons = [
  { name: "Food", uri: require("./images/Food.png") },
  { name: "Mart", uri: require("./images/mart.png") },
  { name: "Car", uri: require("./images/car.png") },
];

const IconSelection = () =>
  Icons.map((icons) => (
    <View>
      <Image source={icons.uri} />
      <Text style={{ textAlign: "center" }}>{icons.name}</Text>
    </View>
  ));

const styles = StyleSheet.create({});

export default IconSelection;

  • Related