0

I have a react-native-modal-dropdown with multiple options. When the user selects an option, changeImage() is triggered and the image path updates from over 150 possible images.

However the following solution doens't update the Image component because react native doesn't allow dynamic require.

const [imagePath,setImagePath] = useState('defaultImg')

// newImg, is a dynamic string which changes with user input
// "assets/images" folder has over 150 images

const changeImage = (newImg) {
  // if valid path, change path
  setImagePath(newImage)
}

return(
 <Image
    style={styles.imageStyle}
    resizeMode="center"
    source={require('../assets/images/' + imagePath + '.png')}
 />)

This solution is not scalable, neither is this.

I've seen some solutions using json and helper methods but I couldn't get them to work.

usersina
  • 1,063
  • 11
  • 28

1 Answers1

0

I've figured it out using an "images.js" helper file.

In "App.js" I'm updating the image path depending on a "target" state value.

import {getImage} from './images';

// Image is updated based on this value
const [target,setTarget] = useState("default");

// Default image path
const [imagePath,setImagePath] = useState({path: getImage('default')}) 

useEffect(() => {
  setImagePath({
    path: getImage(target);
  });
},[target])


return(
  <View>
    <Image source={imagePath.path} />
  </View>
)

And here's "images.js" which is in the same path as a folder called "pictures":

export function getImage(input) {
  switch (input) {
    case "value_1": return require('./pictures/Picture1.png');
    case "value_2": return require('./pictures/Picture2.png');
    case "value_3": return require('./pictures/Picture3.png');
    ...
    case "value_149": return require('./pictures/Picture149.png');
    case "value_150": return require('./pictures/Picture150.png');
    case "default": return require('./pictures/placeholder.png');
  }
}

Creating the above function can be tedious so I created a python script that outputs the switch result programmatically to an output file and I simply copied pasted the output into this file.

usersina
  • 1,063
  • 11
  • 28