DEV Community

Discussion on: Dynamic imports in React-Native

Collapse
 
nuevoleonkx profile image
nuevoleonkx

Can you please provide an example? I want to use with an <Image> element with dynamic source inside a <FlatList>, something like this..

...
import * as ImageLibrary from '../../static/assets/icons';
...
<FlatList
        data={options}
        renderItem={({ item }) => (
          <TouchableHighlight>
            <Image
              source={`ImageLibrary.image${item.icon.split('.').slice(0, -1).join('.')}`}
            />
          </TouchableHighlight>
        )}
      />
...

Is it possible?

Thanks in advance

Collapse
 
thibmaek profile image
Thibault Maekelbergh

Seems like a small syntax error:

import * as ImageLibrary from '../../static/assets/icons';

<FlatList
  renderItem={({ item }) => <Image source={ImageLibrary[`image${item.icon.split('.').slice(0, -1).join('.')}`]} />}
/>

In an example this translates to:

// assets/icons.js
export { default as imageEditIcon } from './edit.png';

// index.js

// With item.icon = editIcon

<Image source={ImageLibrary.imageEditIcon}/>
...

You are using something called a computed key for an object, by taking advantage of template strings to interpolate the value into the string. With interpolation and writing it statically it would be the same as ImageLibrary['imageEditIcon'] which retrieves the value for ImageLibrary.imageEditIcon

Thread Thread
 
nuevoleonkx profile image
nuevoleonkx

i'm really sorry... it was my fault.. that's exactly what i'm trying to do. Thanks a lot!