Search code examples
javascriptreactjsreact-nativerequire

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


Solution

  • 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}