Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native require(image) returns number

I have a js file with one component EventCard, which takes event name, date, event image etc. If event image does not exist I want to load a placeholder image. Now that statement looks like this

constructor(props){
    super(props);
    let imgUrl = props.image ? props.image : require("../assets/images/image.jpg");
    this.state = {image: imgUrl}
}

I am using this.state inside render for source like

source={{uri: this.state.image}}

I strangely get 11 when doing a require for the placeholder image and the react native throws error saying 'value for uri cannot be cast from Double to String'.

Help is much appreciated.

Thanks

like image 357
Kireeti K Avatar asked Sep 19 '18 05:09

Kireeti K


People also ask

How to use dynamic images in React Native?

This solution usually works best for a few images. As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:

How to add React Native assets to Android app?

at the place of YOUR_FOLDER_NAME use the newly created folder's name images or any given NAME Now run npx react-native link in your terminal from main app folder, this will link/add the assets folder in the android bundle. Then rebuild the debug app.

Why is src attribute named source in React Native?

For example, the result of require ('./my-icon.png') might be: In React Native, one interesting decision is that the src attribute is named source and doesn't take a string but an object with a uri attribute. On the infrastructure side, the reason is that it allows us to attach metadata to this object.

How does react native integrate with Metro?

According to the React Native documents, this does several things: This uses the CommonJS function ‘require’, which Metro looks for to know when to place the photo in our bundle. It sets up the Metro bundler (also known as the packager or Metro Server) to include the file photo1.jpg into the bundle, based on the existence of the ‘require’ keyword.


1 Answers

You need to assign image source directly when using require.

constructor(props){
  super(props);
  let imgUrl = props.image ? { uri: props.image } : require("../assets/images/image.jpg");
  this.state = { image: imgUrl };
}

and then in your render:

source={this.state.image}
like image 189
Fawaz Avatar answered Sep 27 '22 17:09

Fawaz