0

I want to import an image into my react native app locally.

render() {

    console.log(this.props.image);   //   this logs '../../images/avatartest.jpg' every time

    let test = require (this.props.image!);   //    bang is required because of interface
    return (
        <ImageBackground
            source={test}
        >
        </ImageBackground>
    );
}

Running this code produces this error:

enter image description here

Is there no way to accept a variable name that has a string?

2
  • you added ! in require require (this.props.image!) Commented Nov 29, 2018 at 15:17
  • @RahulSharma That bang is required to remove an intellisense error. It is the same error with or without it. Commented Nov 29, 2018 at 15:19

2 Answers 2

1

All requires must be statically analyzable. That means you cannot use variables in require.

You can bundle the images in your app manually and the use where variables will work.

<Image source={{ uri: this.props.image }} />
Sign up to request clarification or add additional context in comments.

Comments

0

What you are trying to do here is to dynamically import an image which is not supported, the best way to do this is to require the images beforehand and pass the required value as a prop. Assume that the parent component for your component is ImageView

export default const images = {
   img1:require('IMAGE_URL')
}

//import this in the your view and use it as the prop value 
<ImageView image={images.img1}></ImageView>

The above method will make sure that the packager can locate the image.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.