the image of the openSelectDialog method of the ImagePickerIOS in the React Native is not output - image

Here is my code:
import React, {Component} from 'react';
import {ImagePickerIOS, Image, Text, View} from 'react-native';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
image: ''
};
}
componentDidMount() {
ImagePickerIOS.openSelectDialog({}, imageUri => {
this.setState({ image: imageUri });
}, error => console.log(error));
}
render() {
return (
<View>
<Text>{JSON.stringify(this.state.image)}</Text>
{ this.state.image ?
<Image style={{flex: 1}} source={{uri: this.state.image}} />
: null }
</View>
);
}
}
export default Dashboard
When you run the above code, this.state.image will have "assets-library: //asset/asset.HEIC? Id = .... & ext = HEIC".
However, is not output.
And <Image style={{width: 200, height: 200}} source={{uri: this.state.image}} />
This style property puts the IOS simulator to a black screen and exits the app.
The React Native version is 0.57.4 and the simulator is iPhone X - 12.1.
Help.

I have the same problem. But I have solved this issue.
You may need add width and height to style.
{ this.state.image ? <Image style={{height: 100, width: 100}} source={{uri: this.state.image}} /> : null }

Related

Image not loading in React Native when I use require but loads when I load from URL

When I try to load an image by using require, the image does not load but when I load the same image from a URL, the image loads. Here is the snippet of code that I am calling the image from
class Home extends React.Component {
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
showVerticalSCrollIndicator = {false}
showHorizontalScrollIndicator = {false}
>
{this.state.loading ? (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#5d38aa"
size="large"
/>
) : (
<div>
<Header title={this.state.user.name} />
<div id='image'>
<Image
source={require('./arrow.png')}
style={styles.image}
/>
</div>
</div>
)}
</ScrollView>
);
}
}
The image is loaded here
<Image
source={require('./arrow.png')}
style={styles.image}
/>
Please make sure that you give the right path to your image.
You can use the source as an object:
<Image source={{ uri: 'something.jpg' }} />
But what you have should work, check your path.
There were few errors here and there, I think you were trying to port ReactJS code to RN and not surprisingly there were few slip-ups like you used div instead and View and small things like that, also boxShadow was not working so I removed that.
After a few tweaks code is working and images are loading.
As I stated earlier, I have omitted the User component and sanityClient, you can implement them later.
Here is the working home.js after changes.
import React from "react";
import {
ScrollView,
ActivityIndicator,
StyleSheet,
Image,
ImageBackground,
View,
} from "react-native";
// import UserList from "./user-list";
import Header from "./header";
// import sanityClient from "";
// import BackButton from "./back-button";
// import User from "./user";
// import {Asset} from 'expo-asset';
// const imageURI = Asset.fromModule(require('./arrow.png')).uri;
// const image = require("./assets/aoeu.jpg");
class Home extends React.Component {
state = {
user: {},
loading: true,
};
componentDidMount() {
// TODO: get users
this.getUser();
}
async getUser() {
// sanityClient
// .fetch(
// `*[ _type == "user" && emailAddress.current == "dwight#viamaven.com"]`
// )
// .then((data) => {
// console.log(data);
// this.setState({ user: data[0], loading: false });
// console.log(this.state.user);
// })
// .catch((err) => console.error(err));
// const res = await fetch("https://randomuser.me/api/?results=20");
// const { results} = await res.json();
// // console.log(results)
// this.setState({users: [...results], loading: false});
}
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
showVerticalSCrollIndicator={false}
showHorizontalScrollIndicator={false}
>
{!this.state.loading ? (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#5d38aa"
size="large"
/>
) : (
<View>
<Header title={"Spidy"} />
<View id="image">
<Image source={require("./arrow.png")} style={styles.image} />
</View>
{/* <User /> */}
</View>
)}
</ScrollView>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: "white",
width: 375,
height: 812,
// top: '50px',
},
centering: {
alignItems: "center",
justifyContent: "center",
padding: 8,
height: "100vh",
},
image: {
width: 50,
height: 50,
marginRight: 20,
// boxShadow: "0px 1px 2px 0px rgba(0,0,0,0.1)",
// boxShadow: "10px 10px 17px -12px rgba(0,0,0,0.75)",
},
});
export default Home;
Zip file containing all the changes: src
Output:

Image not showing in React Native Web App. Appears when I build for Android or iOS but doesn't show when using react-scripts start

I am trying to display an image in a React Native Web App which is run using react-scripts start. When I build the App for iOS or Android, the image appears perfectly fine (using expo) but when I build it for the Web App, the image fails to load. Here is the code snippet for the Home component where the image is loaded
import React from "react";
import { ScrollView, ActivityIndicator, StyleSheet, Image, ImageBackground } from "react-native";
import UserList from "./user-list";
import Header from './header';
import sanityClient from './assets/client'
import BackButton from './back-button'
import User from './user'
// import {Asset} from 'expo-asset';
// const imageURI = Asset.fromModule(require('./arrow.png')).uri;
const image = require('./assets/aoeu.jpg');
class Home extends React.Component {
state = {
user: {},
loading: true
};
componentDidMount() {
// TODO: get users
this.getUser();
}
async getUser() {
sanityClient.fetch(`*[ _type == "user" && emailAddress.current == "dwight#viamaven.com"]`)
.then((data) => {
console.log(data);
this.setState({user: data[0], loading: false});
console.log(this.state.user);
})
.catch((err) => console.error(err))
// const res = await fetch("https://randomuser.me/api/?results=20");
// const { results} = await res.json();
// // console.log(results)
// this.setState({users: [...results], loading: false});
}
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
showVerticalSCrollIndicator = {false}
showHorizontalScrollIndicator = {false}
>
{this.state.loading ? (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#5d38aa"
size="large"
/>
) : (
<View>
<Header title={this.state.user.name} />
<View>
<Image
source={require('./arrow.png')}
style={styles.image}
/>
</View>
<User />
</View>
)}
</ScrollView>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: "white",
width: '375px',
height: '812px',
// top: '50px',
},
centering: {
alignItems: "center",
justifyContent: "center",
padding: 8,
height: '100vh'
},
image: {
width: '50px',
height: '50px',
marginRight: 20,
boxShadow: "0 1px 2px 0 rgba(0,0,0,0.1)"
}
});
export default Home;
Here is a link to the GitHub repo where the entire project is stored https://github.com/nimbusdin/stackreactnative
Try to import this way and use it like this
import image = './assets/aoeu.jpg';
<Image
source={image}
style={styles.image}
/>

Replace with a text while encountering onError on Image REACT NATIVE

Just like HTML, we have the opportunity to show a text i.e.
<img src="hello.png" alt="hello" />
There is plenty of suggestions for replacing an image with another image (fallback src), but I need to show a text instead of any other images!
React Native Image onError method will execute on Image when image not found on server or unexpectedly something wrong goes with the connection. Using that you can display text as below,
import React, { Component } from "react";
import { Text, View, Image, StyleSheet } from "react-native";
export default class Example extends Component {
state = {
isLoadingImage: true,
isImageFailed: false
};
onErrorLoadingImage = () => {
this.setState({
isLoadingImage: false,
isImageFailed: true
});
};
render() {
return (
<View style={styles.container}>
{!this.state.isImageFailed ? (
<Image
source={{
uri:
"https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg"
}}
style={styles.imageStyle}
onError={this.onErrorLoadingImage}
/>
) : (
<View style={styles.container}>
<Text>Error loading image</Text>
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
justifyContent: "center",
alignItems: "center"
},
imageStyle: {
resizeMode: "center",
width: "50%",
height: "50%"
}
});
Unfortunately, there is no other way to display text just like HTML alt=" Error loading image "
Hope this will help you.

Using image URL link retrieved from web API to display image in view

After some searching online, I have found some decent code to base my requirements on. I have successfully retrieved data from my web API and display the content on a page view a FlatList. However, the image URL retrieved from the API is not being processed and I am not sure why.
This is my results
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
FlatList,
ActivityIndicator,
Image
} from 'react-native';
//import data from './json/FetchJsonDataExample.json';
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
isLoading: true, // check if json data (online) is fetching
dataSource: [], // store an object of json data
};
}
componentDidMount() {
return fetch("https://www.apakataorang.com/wp-json/wp/v2/posts?per_page=20")
.then((response) => response.json())
.then((responseJson) => {
// set state value
this.setState({
isLoading: false, // already loading
dataSource: responseJson
});
})
.catch((error) => {
ToastAndroid.show(error.toString(), ToastAndroid.SHORT);
});
}
render() {
// show waiting screen when json data is fetching
if(this.state.isLoading) {
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:30}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => {
return (
<View>
<Text style={styles.info}>{item.title.rendered}</Text>
<Image
source={{uri: 'item.jetpack_featured_media_url'}}
style={{width:'100%', height: 200, resizeMode : 'stretch'}}
/>
<Text style={styles.info}>{item.jetpack_featured_media_url}</Text>
</View>
)
}}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
info: {
fontSize: 20,
}
});
Ideally I would like the image to display on the view.
remove single quotes from the Image component's source prop like below :
<Image
source={{uri: item.jetpack_featured_media_url}}
style={{width:'100%', height: 200, resizeMode : 'stretch'}}
/>
If you set 'item.jetpack_featured_media_url' (with a single quote) to the URI it will consider it as a path itself

Changing screen gives undefined props.navigation error react native

I am trying to change screen after few seconds which is for splash screen effect in react native. I have a main screen in which app originates. The code for first screen is:
import HomeUp from './HomeUp'
import Splash from './Splash'
import React, { Component } from "react";
export default class OriginPage extends Component {
constructor(props){
super(props)
this.state = {
component : <Splash />
}
}
componentDidMount(){
// Start counting when the page is loaded
this.timeoutHandle = setTimeout(()=>{
// Add your logic for the transition
this.setState({ component: <HomeUp /> })
}, 5000);
}
componentWillUnmount(){
clearTimeout(this.timeoutHandle);
}
render() {
return (
this.state.component
);
}
}
My splash screen is :
import React from 'react';
import { StatusBar , View , Text , ActivityIndicator } from 'react-native';
export default class Splash extends React.Component {
render() {
return (
<View style={{ flex: 1 , justifyContent: 'center' , alignItems: 'center' , backgroundColor : '#34495e'}}>
<StatusBar backgroundColor="#2c3e50" barStyle="light-content"/>
<Text style={{ color : 'white',fontSize : 18 }}>Hello Splash</Text>
<ActivityIndicator color={'white'}/>
</View>
)
}
}
Till now everything works fine and the screen change over after 5s also working but this below code has bug.
import React, { Component } from "react";
class HomeUp extends Component {
render () {
const { navigate } = this.props.navigation;
return(
<TouchableHighlight onPress={() => navigate("Products", { product: item })} underlayColor="transparent">
<View style={styles.view} >
<Image style={styles.image} source={{uri: item.images[0].src}} />
<Text style={styles.name}>{item.name}</Text>
</View>
</TouchableHighlight>
);
}
}
Loading this screen alone have no bug but while changing screen I get undefined navigation.props error. hanks in adavanced.
If you are deconstructing your navigation props in your HomeUp component you should do it as follows:
const { navigation } = this.props;
Or also:
const navigate = this.props.navigation;
Hope it helps.

Resources