0

Hello I am trying to input a value into an SVG URI in React-Native as follows:

source={require('../tasks/images/' + {task.image} + '.png')} 

I am currently iterating through an array of objects and outputting the svgs for each, so I want to do it this way but the syntax isnt accepted.

Any help or advice is welcome!

Mandalina
  • 446
  • 5
  • 22

2 Answers2

1

Here, you cannot pass dynamic images path which is available locally as your assests.
Moreover if you have image URI which is coming from the server then you can just provide here and it will work like a charm. But for image Path which is present locally you have to provide actual path. More you can read here.

However, what you can do just provide nested if else for the path based on the conditions, but then please note, you have to provide the full path as well.

Example :-

source={this.state.data===1?require('../tasks/images/image1.png'):this.state.data===2?require('../tasks/images/image2.png'):require('../tasks/images/image3.png')} 

Thanks....Hope it helps :)

abhikumar22
  • 1,764
  • 2
  • 11
  • 24
1

Because there is no way to make the string passed to require dynamically, you could have an image collection file that references every image you would need, for example:

Create a file ImageCollection.js with the following:

export default imageCollection={
    "1": require("./image1.png"),
    "2": require("./image2.png"),
    "3": require("./image3.png"),
    "4": require("./image4.png")
}

Then import it into your file where you need to require your images and do something like this:

import Images from './ImageCollection.js';

class YourComponent extends Component {

    renderItem = ({item}) => (
        <View>
            <Text>Image: {item}</Text>
            <Image source={Images[item]}/>
        </View>
    );

    render () {
        const data = ["1","2","3","4","5"]
        return (
            <FlatList data={data} renderItem={this.renderItem}/>
        )
    }
}

export default YourComponent;

But if you really need to pass dynamic image sources then you could use a package like react-native-image-progress which lets you pass a variable as an image source, I wouldn't recommend this approach unless if there is absolutely no other way for you to solve this problem.

David Porcel
  • 290
  • 1
  • 6