N Kaushik

How to add dynamic image source in react native

July 27, 2020

In react native, we can add one local image to an Image component using a source props :

<Image source={require("./images/logo.png")} />

But, if we want to add the image path dynamically, it doesn’t work :

<Image source={require(`./images/${props.image}.png`)} />

It will throw one error.

To solve this problem, we can use one switch-case block :

const getImage = name => { switch (name) { case "logo": return require("../../images/logo.png") default: return require("../../images/thumbnail.png") } }

Subscribe to my Newsletter

© 2021, nkaushik