⌨️
Web Design
  • Index
  • Front End
    • Front End Index
  • HTML/CSS/JS
    • HTML Index
      • Page layout
      • Form
      • Image Optimization
    • CSS Index
      • CSS Selectors
        • Selectors
        • Combinators
        • Attribute Selectors
        • Pseudo classes
      • CSS Cascade and Inheritance
        • Cascade
        • Inheritance
      • Specificity
      • Box Model
      • CSS Clearfix
      • Responsive Meta Tag
      • Flexbox Layout
      • Grid Layout
      • CSS Naming Rules
        • Golden Guidelines for Writing Clean CSS
        • BEM
        • Rules
      • Frameworks & Libraries
    • JS Index
      • JS loading
      • Modules
      • Js Array Common Method 1
      • Js Array Common Method 2
      • Custom attributes on the element
      • Operator
      • Parse a JSON Date in JavaScript
      • Importmap
  • Git
    • Git Index
    • Initialize a Repository
    • Top 20 Git Commands With Examples
  • UML
    • UML Class
  • React
    • Index
      • setState async issue
      • Redux
      • Axios
      • useState update in A Timeout
  • WebGL
    • WebGL Index
  • Back End
    • Back-End Index
      • Knex
      • Bookshelf
        • bookshelf install
        • Bookshelf only returns one row
      • Server side init flow
      • Install Wordpress on Ubuntu 22.04 with a LAMP Stack
  • React Native
    • React Native Index
      • Dynamically changing Image URLs in React Native
  • Expo
    • EAS build config
Powered by GitBook
On this page

Was this helpful?

  1. React Native
  2. React Native Index

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()}
/>
PreviousReact Native IndexNextEAS build config

Last updated 2 years ago

Was this helpful?