Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <Image> with a local file

Tags:

react-native

The documentation says that the only way to reference a static image is to use require.

But I'm not sure where does react expect to have those images. The examples don't have any domain, so it seems like you have to go to Xcode and add them to Images.xcassets, but that didn't work for me.

like image 529
Blai Pratdesaba Avatar asked Mar 26 '15 23:03

Blai Pratdesaba


People also ask

Can I use an image from my local file system as background in HTML?

"is this a security feature of the browser trying to block external domains from accessing the user's local resources" Yes. This used to be possible but modern browsers block file:// links from working when loaded in a non- file: url.

How do you call a local image in HTML?

To link to a target file in the same directory as the invoking HTML file, just use the filename, e.g. my-image. jpg . To reference a file in a subdirectory, write the directory name in front of the path, plus a forward slash, e.g. subdirectory/my-image. jpg .


2 Answers

Using React Native 0.41 (in March 2017), targeting iOS, I just found it as easy as:

<Image source={require('./myimage.png')} /> 

The image file must exist in the same folder as the .js file requiring it for "./" to work.

I didn't have to change anything in the XCode project. It just worked.

Note that the path seems to have to start with "./" or "../" and be full lower case. I'm not sure what all the restrictions are, but start simple and work forward.

Hope this helps someone, as many other answers here seem overly complex and full of (naughty) off-site links.

UPDATE: BTW - The official documentation for this is here: https://reactnative.dev/docs/images

like image 105
spechter Avatar answered Sep 20 '22 05:09

spechter


It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

like image 35
syrnick Avatar answered Sep 23 '22 05:09

syrnick