Home > Article > Web Front-end > How to Display Dynamically Named Images in React Native?
Dynamic Image Names in React Native: Using the Image Require Module
When working with React Native, the Image module allows you to display images in your applications. Typically, images can be referenced statically using the require('image!name-of-the-asset') syntax.
However, a common question arises when attempting to use dynamic image names. For instance, if you have a dynamic string representing an image name, such as 'avatar', the following code will not work:
<Image source={require('image!' + 'avatar')} />
This will result in the error "Requiring unknown module "image!avatar"".
Explanation
According to the React Native documentation, static resources must be referenced directly using the static syntax mentioned earlier. Dynamically loading images is not supported.
// Correct: <Image source={require('image!my-icon')} /> // Incorrect: var icon = 'my-icon-active'; <Image source={require('image!' + icon)} />
Alternative Solution
If you need to use dynamic image names, you can store the image assets in a separate array or object and then reference them using the source prop of the Image component:
const images = { avatar: require('image!avatar'), logo: require('image!logo'), }; <Image source={images[dynamicImageName]} />
Additional Note
For iOS, you must remember to include your images in an asset catalog within your Xcode project. This is necessary for images to be correctly referenced in your React Native application.
The above is the detailed content of How to Display Dynamically Named Images in React Native?. For more information, please follow other related articles on the PHP Chinese website!