Sometimes, we want to require image module using dynamic names with React Native.
In this article, we’ll look at how to require image module using dynamic names with React Native.
How to require image module using dynamic names with React Native?
To require image module using dynamic names with React Native, we can call require
with different image path strings according to another value.
For instance, we write:
import * as React from 'react';
import { View, Image, Button } from 'react-native';
import { Card } from 'react-native-paper';
const App = () => {
const [showFirstImg, setShowFirstImg] = React.useState(true);
return (
<View>
<Button title="toggle" onPress={() => setShowFirstImg((s) => !s)} />
{showFirstImg ? (
<Image source={require('./test1.png')} />
) : (
<Image source={require('./test2.jpg')} />
)}
</View>
);
};
export default App;
to add 2 Image
s with different source
values.
We call require
to include the images in the component.
And we use the showFirstImg
to control which image is shown.
We add a Button
to toggles the showFirstImg
value when pressed.
Conclusion
To require image module using dynamic names with React Native, we can call require
with different image path strings according to another value.