2

I am new to react native and having some issues with react image component. I read the documentation and searched several articles and questions asked on stack overflow. I got the idea that src of Image component can either take a string (either a path from local or a url) , or we can use require with string as perimeter to load an image. The project I am working on has over 50 images, and the ones to render are decided on runtime. Before, I planned on using variables as require perimeter to load images dynamically, but on research it came to my knowledge that it is not possible to do that, and react native has no plan on providing such feature.

I came with an idea to create an object containing require as a value.

export const subCategories = {
  'protection':[
     [
      {
        imageUrl: require('../imag`enter code here`es/trees.png'),
        title: 'Protection',
        value: 'p_1'
      },
      {
        imageUrl: require('../images/eco-tag.png'),
        title: "From Enemy",
        value: 'p_2'

      },
      {...

   'daily':[
     [
      {
        imageUrl: require('../images/trees.png'),
        title: 'Morning',
        value: 'd_1'
      },
      {
        imageUrl: require('../images/eco-tag.png'),
        title: "Evening",
        value: 'd_2'

      },
      {...

And decide which object to select based on navigation perimeter passed to the component.

this.state = {
            data: subCategories[this.props.navigation.state.params.value]
    ...

And I had success with this. But I have a concern of application performance since I do not have complete knowledge and don't know how does this statement behave

imageUrl: require('../images/eco-tag.png')

Will it load all the images into the memory, and render the one allocated to the source of Image component. Or will load the Image at the time of rendering?

<Image source={ this.props.imageUrl } style = { styles.image }  />

If you explain this to me on your own, please do so. And if you have a good article or have missed any part of the documentation. please redirect me to it.

PS: I am exporting data in a JS file, and importing it when redirected to a screen. I would also love to know if this is the correct way.

Asjad Amin
  • 21
  • 2

1 Answers1

0

For render time require try using a function:

 {
    imageUrl: () => require('../trees.png'),
    title: 'Protection',
    value: 'p_1'
  }

and in the component:

<Image source={ this.props.imageUrl() } style = { styles.image }  />