When I am trying to load image from props i am getting the following error
warning: failed prop type: invalid prop source supplied to image
Here is my code
src/components/common/Header.js
<View style={viewStyle}>
<Text style={textStyle}>{props.children}</Text>
<Image style={{height:25, width:25}} source={props.imageUri} />
</View>
src/index.js
<Header imageUri='../../images/logout.png'>My App</Header>
and the image is at path src/images/logout.png
please help
As the React Native Documentation says, all your images sources need to be loaded before compiling your bundle.
Adding a simple image in React Native should be like this:
<Image source={require('./path_to_your_image.png')} />
Let's say you have this:
const slides = {
car: './car.png',
phone: '../phone.png',
}
Then you pass slides as a parameter but still, you won't be able to use it like this (even though logically should work):
<Image source={require(props.car)} />
Use require() inside the sildes{}
const slides = {
car: require('./car.png'),
phone: require('../phone.png'),
}
And then use it like this:
<Image source={props.car}/>
your source is wrong.
It should use uri properties.
Either you use require:
<Image source={require('.../../images/logout.png')} />
in turn, you can then require this prop too
<Image source={require(props.imageUri)} />
Or you use the Uri as is:
<Image source={{uri: props.imageUri }} />
Refer to the documentation for more details here
Using the below method gives error in react-native:
<Image style={{height:25, width:25}} source={require(props.imageUri)} />
Instead use:
<Image style={{height:25, width:25}} source={props.imageUri}/>
And pass the below code as imageUri prop from the Parent component.
require('./public/images/image.png')
It has worked for me and hope this will help others.
you can set source of image from props like this :
in component :
<Image source={props.path} >
and pass source to component like this:
in parent :
<
.
.
path={require("../assets/images/icon.svg")}
.
.
>
For a local image path the syntax is
<Image style={{height:25, width:25}} source={require(props.imageUri)} />
<Image
source={this.props.imgUri}
style={{
height: 30,
width: 30,
resizeMode: 'contain',
}}
/>
call it
<StyledInput text="NAME" imgUri={require('../assets/userIcon.png')} ></StyledInput>
You can place Image directly in the Component, as a prop children.
<ComponentA>
<Image source={require('./src/assets/localisation-icon.svg')} />
</ComponentA>
The Component A will be composed of
function ComponentA(props) {
return (<View> {props.children} </View>);
}
This will render the image.
in your express.js server, set up a static directory containing any image.jpg:
const express = require('express')
const app = express()
app.use(express.static(path.join(__dirname, '../path_to/..', staticImages)))
react native component:
return <Image source={{ uri: `http://192.168.0.1:3345/${'image.jpg'}`}} />
Related
I see This Component in official site of React Native. But nothing Example get on the https://reactnative.dev/docs/image#loadingindicatorsource. I only get what is this
Can anyone tell me how I use this Component on react native ?
<Image {...props} loadingIndicatorSource={URI} />
What does statement above mean?
{...props} - is your custom props, like source or style, for example.
URI - is URI of image, which will be shown while image, specified in source props, is loading.`
Examples:
<Image source={{uri: URI}} loadingIndicatorSource={require('loadingIndicatorSource={require('#assets/images/loading.jpeg')}')}
<Image source={{uri: URI}}
loadingIndicatorSource={{uri:
'https://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/128/Emotes-face-smile-icon.png'}} />
You can use loadingindicator like as activityindicator
<Image
style={{
width: "100%",
height: "85%",
alignSelf: "center",
}}
resizeMode="contain"
loadingIndicatorSource={require("../assets/loader2.gif")}
source={{ uri: item.thumb_url }}
/>
One of the ways I found to use it is passing a component directly, like an ActivityIndicator
<Image loadingIndicatorSource={<YOUR LOADING COMPONENT/>} />
Hi I have iumages in local path in react native and I'm trying to provide path as
<ListItem
roundAvatar
avatar={<Avatar
rounded
source={require( '../../../public/images/'+props.item.ImageName+'.png')}
title={props.item.cat_name}
/>}
onPress={() => props.subscreen(props.item._id)}
key={props.item._id}
title={props.item.cat_name}
/>
But it shows error
on printing image path on console it shows string only. What can be other way around or where is mistake?
You can't use variables in a require, only a string, not a variable.
You need do this:
avatar={<Avatar
rounded
source={require( '../../../public/images/nameOfPic.png')}
title={props.item.cat_name}
/>}
if you wanna choose a image you can do like this.
arrayImgs = [require('../../anyName1.jpg'), require('../../anyName2.jpg')];
...
<ListItem
roundAvatar
avatar={<Avatar
rounded
source={isTrue?arrayImgs[0]:arrayImgs[1]}
title={props.item.cat_name}
/>}
onPress={() => props.subscreen(props.item._id)}
key={props.item._id}
title={props.item.cat_name}
/>
EDIT:
You can use URI for local images.
let imagePath = 'file:///storage/emulated/0/Pictures/'+imageName+'.png'
...
<Image
style={{width: '100%', height: 400}}
resizeMode='contain'
source={{imagePath}}
/>
this is a default path for a folder in your Android, try to use any image in your 'Pictures' folder.
Try this:
require(`../../../public/images/${props.item.ImageName}.png`)
The quotes are not the same type.
I have a problem with onLayout in Image:
I have a function to display the dimension.
measureView(event) {
console.log(event.nativeEvent.layout.width);
console.log(event.nativeEvent.layout.height);
}
This Works and shows me the dimension of the TouchableWithoutFeedback
<TouchableWithoutFeedback
style={styles.touchableWithoutFeedback}
onLayout={(event) => this.measureView(event)}>
<Image style={styles.image}
source={require("./../assets/images/photo_1.jpg")}/>
</TouchableWithoutFeedback>
But With the onLayout in the Image, i got nothing, just undefined.
<TouchableWithoutFeedback
style={styles.touchableWithoutFeedback}>
<Image style={styles.image}
source={require("./../assets/images/photo_1.jpg")}
onLayout={(event) => this.measureView(event)}/>
</TouchableWithoutFeedback>
Do you have an Idea why?
Thanks!
I had this problem recently as well. It looks like the <Image /> component mounts before the actual image gets loaded into the container. You probably want to instead use the onLoad property of <Image />. Once you do that you can pretty much proceed as normal...
<Image
onLoad={event => { console.log(event.nativeEvent.source); }}
source={require("./../assets/images/photo_1.jpg")}
style={styles.image}
/>
// Would log { height: 123, url: 'somestring', width: 123 }
Keep in mind that may or may not only work for static resources. I'm not 100% that network images provide a size through that function.
Good luck! :)
I'm trying to access the HTML source code of a 3rd party web page to read a specific DOM element value of a page which is loaded in WebView component in react-native.
<WebView
source={{uri: 'https://www.amazon.com'}}
/>
and Suppose there's a DOM element like this:
<span class="price bold some-class-name">$459.00</span>
I also tried this component but could not do that:
https://github.com/alinz/react-native-webview-bridge
Is there any way to get the current HTML source code of page inside a WebView and Read specific DOM element value?
Looks like this functionality was added in React Native v0.37. Adding an onMessage parameter will inject a postMessage variable into your WebView. You can then just inject JavaScript as normal, select your element and postMessage it back.
render (
const jsCode = "window.postMessage(document.getElementsByClassName("price bold some-class-name"))"
return (
<View style={styles.container}>
<WebView
source={{uri: "http://..."}}
onMessage={this._onMessage}
injectedJavaScript={jsCode}
/>
</View>
);
)
The answer by Brian F is great and helped me a lot. There is just one thing missing. You need to append ReactNativeWebView to the postMessage function.
So it would look like
render (
const jsCode = "window.ReactNativeWebView.postMessage(document.getElementsByClassName("price bold some-class-name"))"
return (
<View style={styles.container}>
<WebView
source={{uri: "http://..."}}
onMessage={this._onMessage}
injectedJavaScript={jsCode}
/>
</View>
);
)
In my experience, It will work well, because I've tried to get product information from Amazon and Taobao, Rakuten.
_onMessage = (message) => {
// you can put processing code here.
}
render (
const jsCode = "window.ReactNativeWebView.postMessage(document.getElementsByClassName("class name"))"
// or you can use `document.querySelector("element query")` instead of `document.getElementsByClassName("class name")`
return (
<View style={styles.container}>
<WebView
source={{uri: "url here"}}
onMessage={this._onMessage}
injectedJavaScript={jsCode}
/>
</View>
);
)
For those who are still not getting then try this for the latest react-native
window.ReactNativeWebView.postMessage(document.getElementById('id_here').innerHTML);
const INJECT_JS = `window.ReactNativeWebView.postMessage(document.getElementById('id_here').innerHTML);
alert("Hel0....")
`
return (
<View style={styles.container}>
<WebView
source={{uri: "http://..."}}
onMessage={event => {
console.log(event.nativeEvent.data);
}}
injectedJavaScript={INJECT_JS }
/>
</View>
);
<WebView
source={{html: "<span class="price bold some-class-name">$459.00</span>"
/>
or you can right your template into a constant, then do this:
const HTMLTemplate = `<span class="price bold some-class-name">$459.00</span>`;
<WebView
source={{html: HTMLTemplate}}
/>
Given below code, react native complains
Requiring unknown module "../../images/Foo.png".If you are sure the module is there, try restarting the packager or running "npm install".
But the same code works fine if I hardcode the image source path in require call.
Code not working: has a method call to determine icon name. Notice the require('../../images/'+imageIconNameFor(prediction.type) line.
const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
<View style={styles.predictionItem}>
<Image style={styles.predictionIcon} source={require('../../images/'+imageIconNameFor(prediction.type))}></Image>
</View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
return "Foo.png";
}
Code working: Instead of calling a method to determine icon name, if I hardcode the icon name in require call, it works fine. Notice the require('../../images/Foo.png') line.
const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
<View style={styles.predictionItem}>
<Image style={styles.predictionIcon} source={require('../../images/Foo.png')}></Image>
</View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
return "Foo.png";
}
Why is there a different behavior when I concatenate strings to build image source?
Why require('../../images/'+imageIconNameFor(prediction.type) fails to render image but require('../../images/Foo.png') works fine? Note that method call was not a problem. Error message contains the complete path of the image computed using the method call. In spite of the complete path, react native complained about missing module with require.
React native version is 0.37.0. I tested this on ios-simulator.
Unfortunately, this is how react-native packager works, the image name in require has to be known statically. Here is example from official docs:
// GOOD
<Image source={require('./my-icon.png')} />
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />
// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />
make sure give some style like this
<Image source={{uri: 'https://reactjs.org/logo-og.png'}}
style={{width: 400, height: 400}} />