Home > Enterprise >  Change the images based on the item's categories react native
Change the images based on the item's categories react native

Time:10-25

I'm making a budget tracker app. And I'm implementing the functions display and add transactions for the app. However, I'm struggling to find a way to dynamically set the image URL (the icon) based on the transaction category type.

The app is written in React Native.

For example, I have a list of transactions as below:

[
  {
    id: 1,
    type: 'Expense',
    category: 'Food',
    description: 'Burger',
    amount: 100,
    date: '2020-10-10',
    createdAt: '2021-01-01',
  },
  {
    id: 2,
    type: 'Expense',
    category: 'Entertainment',
    description: 'Movie',
    amount: 200,
    date: '2020-10-10',
    createdAt: '2021-10-02',
  },
  {
    id: 3,
    type: 'Income',
    category: 'Salary',
    description: 'Salary',
    amount: 1000,
    date: '2020-10-10',
    createdAt: '2021-10-03',
  },
  {
    id: 4,
    type: 'Expense',
    category: 'Food',
    description: 'Burger',
    amount: 100,
    date: '2020-10-10',
    createdAt: '2021-01-01',
  },
]

Then I want to display it in a list, and each list item contains the icon representing the category, like this image: enter image description here

CodePudding user response:

You can just import images and add them as a key like this :

import burgerImage from '../images/burger.jpg';
import movieImage from '../images/movie.jpg';

[
  {
    id: 1,
    type: 'Expense',
    category: 'Food',
    description: 'Burger',
    amount: 100,
    date: '2020-10-10',
    createdAt: '2021-01-01',
    icon: burgerImage,

  },
  {
    id: 2,
    type: 'Expense',
    category: 'Entertainment',
    description: 'Movie',
    amount: 200,
    date: '2020-10-10',
    createdAt: '2021-10-02',
    icon: movieImage
  },
]

Pass the icon key as a source to Image component like this :

data.map((datum)=> <Image source={datum.icon} />);

CodePudding user response:

I think you should use category field to render icon be like:

const renderIcon = (icon) => {
  switch (icon) {
    case "Food":
      return <Icon icon="food" />
    case "Movie":
      return <Icon icon="movie" />
    // Diff case
    default:
      return <Icon icon="iconDefault" />
}

And in renderItem of FlatList:

const renderItem = ({ item, index }) => {
  return (
    // render wrapper
    {renderIcon(item.category)}
    // render name, time, price of product
  )
}
  • Related