Doing this my code works fine
<Image
source={require('../../assets/images/music_star.png')}
style={styles.musicStar}
/>
But doing this gives me an error
let imgSource = '../../assets/images/music_star.png';
<Image
source={require(imgSource)}
style={styles.musicStar}
/>
I get an error:
Requiring unknown module "../../assets/images/music_star.png"
What am I doing wrong? How to require images stored in a variable in react-native 0.14.2?
Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage. png) inside this folder. We will show images on the home screen.
Open App. js and add the following code: import { StatusBar } from "expo-status-bar"; import React from "react"; import { StyleSheet, Text, View, ImageBackground } from "react-native"; const staticImage = require("./src/assets/static-image. png"); export default function App() { return ( <View style={styles.
To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.
To use one Image as the header image, we need to pass it as the headerTitle. We can pass one function to headerTitle props that return one Image which will be used as the header image. We can give the height and width of the title image to make it fit in the header.
You can read more in the docs but basically, in order for this to work, 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');
To pass an image from parent to child, you should require it in the parent:
/**
* The entry point for the iOS app.
*/
import React, {
AppRegistry,
Component,
Image,
View,
} from 'react-native';
class Child extends Component {
render() {
return (
<Image source={this.props.image} />
)
}
}
export default class Parent extends Component {
render() {
return (
<View>
<Child image={require('./test.png')} />
</View>
);
}
}
AppRegistry.registerComponent('App', () => Parent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With