Where to put images in a react-native project? - react-native

I am working on a react-native project and we are putting images currently in /images/ folder. Is it a good path for them ? Is there any best practice?

You can add image folder to src(src/image/index.js). Image folder add index.js file create and add whole app image.
In index.js file set
export const IMAGENAME = require('./icon.png');
When import image folder
import { IMAGENAME } from '../image';
Use image:
<Image source={ IMAGENAME } />
You can add image to image folder and set path to index file.
Hope this will help you.

To add a static image to your app, place it somewhere in your source code tree and reference it like this:
<Image source={require('./my-icon.png')} />
please see the below link for more explanation:
https://reactnative.dev/docs/images

In image assets folder, create index.js file and put following:
const images = {
main_bg: require('./background.png'),
main_logo: require('./auth/home_title.png'),
///you can add more many images like this here.
};
module.exports = images;
When using the images, you can do like this:
import Images from '../../assets/index';
...

first create file "ImagesAssets.js" in folder assets.
export const ImagesAssets = {
bannerList1: require('./silver.png'),
bannerList2: require('./gold.png'),
bannerList3: require('./dimound.png'),
bannerList4: require('./busniss.png'),
///you can add more many images like this here.
};
then import the object to "any page" and use it.
import{ ImagesAssets } from '../assets/ImagesAssets';
<View style={styles.itemsContiner}>
<View style={styles.item}>
<Image style={styles.imgBanner} source={ImagesAssets.bannerList1}/>
</View>
<View style={styles.item}>
<Image style={styles.imgBanner} source={ImagesAssets.bannerList2} />
</View>
</View>

Related

React Native: cannot display a local image with Image

I ran the AwesomeProject from environment setup section and I tried to display an image with this code in App.js:
import { View, Image } from 'react-native';
export default function App() {
return (
<View>
<Image source={require('./assets/favicon.png')} />
</View>
);
}
I tried all solution from this post already...
Where the folder structure is:
assets/
favicon.png
App.js
package.json
But nothing displays on the front-end, blank screen (I am watching the change on my web browser).

Icon showing wrong react-native-vector-icon (icomoon)

I need to show SVG icons inside my application, I did the entire process of installing the react-native-vector-icons library and configuring icomon. Also, I went to the icomon website and created my font files. But when I use it, the application renders an icon different from the one I should be reloaded by the file.
config icomon
import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from '../../assets/customIcons/selection.json';
export default createIconSetFromIcoMoon(
icoMoonConfig,
);
icon that should be loaded.
icon being loaded
My code
export function ItemMenuDropdown({ item }) {
const navigation = useNavigation();
return (
<Container onPress={() => navigation.navigate(item.navigation)}>
<Content>
<CustomIcon name="pencil" size={normalize(18)} color="#F68B1F" />
<Text>{item.item}</Text>
</Content>
</Container>
)
I've looked for several solutions here on the site, but I haven't found one that works. Can someone help me?
I think the problem is in your selection.json file. It's either out of date or you're having some kind of cache problem. Maybe you want to try the same operation using this module.
react-icomoon

Reusable Button with image tag (React Native)

I want to turn this section of code into a reusable component so I don't have to write the same thing out 5 times.
<TouchableOpacity onPress={console.log('pressed')}>
<Image
source={require('../img/button_australia.png')}
/>
</TouchableOpacity>
The new component I made to mirror this is as follows:
import React from 'react';
import { Image, TouchableOpacity } from 'react-native';
const ImgButton = ({ onPress, img }) => {
return (
<TouchableOpacity onPress={onPress}>
<Image
source={require(img)}
/>
</TouchableOpacity>
);
};
export { ImgButton };
After importing this component ImgButton I call it with this block of code:
<ImgButton
onPress={console.log("pressed")}
img={'../img/button_australia.png'}
/>
I get the error: "Requiring unknown module '../img/button_australia.png'"
I assume I've gone wrong when passing the string down as a prop but from the examples I've looked I don't see what's wrong with what I've done. Thanks :)
As discussed in this react-native issue, it's not possible to require assets or javascript modules with dynamically generated names, e.g. variables.
This is because the React Native packager uses require (and import) statements to generate the module and asset bundles at compile-time, so the value of the variable is not known.
The simplest way is to just pass the image source to the component directly:
<ImgButton
onPress={console.log("pressed")}
img={require('../img/button_australia.png')}
/>

What is the correct syntax for import images

I recently started using React Native and have problem with displaying local and external Images on Android emulator (Pepperoni starter kit). In example I have Simple component:
class SomeView extends React.Component {
render() {
const a = require("image!somepic")
console.log(a)
return (
<View>
<Image source={require("image!somepic")} style={styles.img}>
<Text>?</Text>
</Image>
<Image source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} style={[styles.img, { width: 50, height: 50 }]}>
<Text>?</Text>
</Image>
</View>
)
}
}
And here is what I got:
Though, in real device, external image was loaded, but local also was not loaded.
What I got in console (is object for local image):
{
"__packager_asset":true,
"path":"D:\\Dev\\pepperoni-app-kit\\images\\somepic#3x.png",
"uri":"somepic",
"width":15.333333333333334,
"height":45.333333333333336,
"deprecated":true
}
I’m using React Native on Windows 10, ReactNative version 0.28.0. Local images located at folder ./images/. (I include several sizes: somepic.png, somepic#2x.png, somepic#3.png.)
The syntax that you are using to import images is the old syntax. The new syntax is
<Image source={require("./images/somepic.png")}/>
See Image guide for more details.

Use <Image> with a local file

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.
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
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.
ES6 solution:
import DefaultImage from '../assets/image.png';
const DEFAULT_IMAGE = Image.resolveAssetSource(DefaultImage).uri;
and then:
<Image source={{uri: DEFAULT_IMAGE}} />
If loading images dynamically one can create a .js file like following and do require in it.
export const data = [
{
id: "1",
text: "blablabla1",
imageLink: require('../assets/first-image.png')
},
{
id: "2",
text: "blablabla2",
imageLink: require('../assets/second-image.png')
}
]
In your component .js file
import {data} from './js-u-created-above';
...
function UsageExample({item}) {
<View>
<Image style={...} source={item.imageLink} />
</View>
}
function ComponentName() {
const elements = data.map(item => <UsageExample key={item.id} item={item}/> );
return (...);
}
I had this exact same issue until I realized I hadn't put the image in my Image.xcassets. I was able to drag and drop it into Xcode with Image.xcassets open and after rebuilding, it fixed the problem!
To display image from local folder, you need to write down code:
<Image source={require('../assets/self.png')}/>
Here I have put my image in asset folder.
From the UIExplorer sample app:
Static assets should be required by prefixing with image! and are located in the app bundle.
So like this:
render: function() {
return (
<View style={styles.horizontal}>
<Image source={require('image!uie_thumb_normal')} style={styles.icon} />
<Image source={require('image!uie_thumb_selected')} style={styles.icon} />
<Image source={require('image!uie_comment_normal')} style={styles.icon} />
<Image source={require('image!uie_comment_highlighted')} style={styles.icon} />
</View>
);
}
I was having trouble with react-native-navigation, I created my own header component, then inserted a image - as logo - on the left before title, then when I was triggering navigate to another screen and then back again, logo was loading again, with a timeout near 1s, my file were local. My solution :
Logo.json
{"file" : "base64 big string"}
App.js
import Logo from '.../Logo.json'
...
<Image source={{uri:Logo.file}} />
We can do like below:
const item= {
image: require("../../assets/dashboard/project1.jpeg"),
location: "Chennai",
status: 1,
projectId: 1
}
<Image source={item.image} style={[{ width: 150, height: 150}]} />
This from https://github.com/facebook/react-native/issues/282 worked for me:
adekbadek commented on Nov 11, 2015
It should be mentioned that you don't have to put the images in Images.xcassets - you just put them in the project root and then just require('./myimage.png') as #anback wrote
Look at this SO answer and the pull it references
For typescript user
import { ImageSourcePropType } from 'react-native'
type Data = {
image:ImageSourcePropType
}
const data:Data = {
image:require('../.../log.png')
}
and then
<Image source={data.image}/>
You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:
<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />
remember then to set the width and height via the style property:
var styles = StyleSheet.create({
image:{
width: 360,
height: 40,
}
});