0

What I'm trying to do

I wanna write mCategories's on in require in source of Image tag.

Code

const mCategories = [
  {
    id: 1, name: 'All', off: 'all_on', on: 'all_on',
  }, {
    id: 2, name: 'Whole Cakes', off: 'wc', on: 'wc_on',
  },
  {
    id: 3, name: 'Sliced Cakes', off: 'sc', on: 'sc_on',
  }, {
    id: 4, name: 'Chilled Items', off: 'chilled', on: 'chilled_on',
  },
];

export default class Category extends React.Component {
  render() {
    return mCategories.map((mCategory) => (
      <TouchableOpacity
        key={mCategory.id}
      >
        <Image
          source={require(`app/assets/ico/ico_category_${mCategory.on}.png`)}
        />
        <Text>{mCategory.name}</Text>
      </TouchableOpacity>
    ));
  }
}

Error

Invalid call at line 28: require("app/assets/ico/ico_category_" + mCategory.on + ".png")

Wes
  • 89
  • 2
  • 9
  • please read this https://stackoverflow.com/questions/44991669/react-native-require-with-dynamic-string?rq=1 – Vova Aug 20 '20 at 07:44

2 Answers2

0

You have two option

1- create a file with image required - React native images must be loaded this way.

export const friendsandfoe = require('./image1.png'); 
export const lifeanddeath = require('./image2.png'); 
export const homeandgarden = require('./image3.png');

after that

import * as images from '../../assets';

and

<Image source={images[`${imageValue}`]}></Image>

=================================================================

2- use this syntax

<Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />

===========================================================================

Mehrad Farahnak
  • 111
  • 2
  • 9
0

I should have made it like this at first.

This Worked!

const mCategories = [
  {
    id: null,
    name: 'All',
    on: require('app/assets/ico/ico_category_all_on.png'),
  },
  {
    id: 1,
    name: 'Whole Cakes',
    on: require('app/assets/ico/ico_category_wc_on.png'),
  },
];

export default class Category extends React.Component {
  render() {
    return mCategories.map((mCategory) => (
      <TouchableOpacity
        key={mCategory.id}
      >
        <Image
          source={mCategory.on}
        />
        <Text>{mCategory.name}</Text>
      </TouchableOpacity>
    ));
  }
}
Wes
  • 89
  • 2
  • 9