Dynamically changing Image URLs in React Native

The image name in require has to be known statically.

// GOOD
<Image source={require('./my-icon.png')} />;

// BAD
var icon = this.props.active
  ? 'my-icon-active'
  : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;

Solution:

const [towerName, setTowerName] = useState('archer')

const tower =()=>{
    switch (towerName) {
      case 'archer': return require('../assets/towers/archer.png')
      case 'mage': return require('../assets/towers/mage.png')
      case 'militia': return require('../assets/towers/militia.png')
      case 'bombard': return require('../assets/towers/bombard.png')
      default: return require('../assets/towers/archer.png')
    }
}

const changeUrl = (towerName) => {
  setTowerName(towerName)
}

<Image 
    source={tower()}
/>

Last updated