re: Dynamic imports in React-Native VIEW POST


Nice! I modified it a little bit to take advantage of full ESM and non dynamic CJS requires:


export { default as imageAlert } from './alert.png';


const fs = require("fs");

const files = fs.readdirSync("./src/common/assets/images")
  .filter(x => x.includes("png"))
  .filter(x => !x.includes('@2x'))
  .filter(x => !x.includes('@3x'));

const res = files.map(file =>`export { default as image${file.split('.png')[0]} } from './${file}';`)

fs.writeFileSync("./src/common/assets/images/index.js", res);


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';
        renderItem={({ item }) => (
              source={`ImageLibrary.image${item.icon.split('.').slice(0, -1).join('.')}`}

Is it possible?

Thanks in advance


Seems like a small syntax error:

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

  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

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

code of conduct - report abuse