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 - image

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}
/>

Related

React Native Expo (Image Picker) is not displaying the Images

Please help me out with this problem.
I can able to pick the image from my Local storage. In the Console also it is showing, But I cannot able to display it on the screen.
Here is my code.
import * as ImagePicker from "expo-image-picker";
import React, { useState } from "react";
import {
ActivityIndicator,
Button,
FlatList,
Image,
StyleSheet,
Text,
useWindowDimensions,
View
} from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
export default function App() {
const [images, setImages] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const pickImages = async () => {
// No permissions request is necessary for launching the image library
setIsLoading(true);
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
// allowsEditing: true,
allowsMultipleSelection: true,
selectionLimit: 10,
aspect: [4, 3],
quality: 1,
});
setIsLoading(false);
console.log(result);
if (!result.canceled) {
setImages(result.uri ? [result.uri] : result.selected);
}
};
return (
<>
<FlatList
data={images}
renderItem={({ item }) => (
<Image
source={{ uri: item.uri }}
style={{ width: 100, height: 100 }}
/>
)}
keyExtractor={(item) => item.uri}
contentContainerStyle={{ marginVertical: 50, paddingBottom: 50 }}
ListHeaderComponent={
isLoading ? (
<View>
<Text
style={{ fontSize: 20, fontWeight: "bold", textAlign: "center" }}
>
Loading...
</Text>
<ActivityIndicator size={"large"} />
</View>
) : (
<Button title="Pick images" onPress={pickImages} />
)
}
/>
</>
);
}
I can able to pick the image from my Local storage. In Console also it is showing, But i cannot able to display it in screen.
Kindly help me out.
It looks like you're already passing the uri into the array. by doing [result.uri] and then in the image you're doing it again item.uri. trying just doing the item.

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:

React-Native Show an image illustration when there is no network (No internet connection status)

I am (newbie) working on an iOS app using react-native. I want to show an image illustration when app goes offline or there is no internet connection to inform the user. I have done all set up required such as :-
1. My image is at src/assets folder
2. using this image in screen - which will be displayed when app detects no internet connection.
In iOS simulator it works fine, but when I run it on iPhone it does not show that image only text appears.
NoInternetScreen.js
import React from 'react';
import {View, StyleSheet, Image, Text} from 'react-native';
const NoInternetScreen = props => {
return(
<View style={styles.imageContainer}>
<Image style={styles.image} source={require('../assets/NoConnection.png')}/>
<View style={styles.textContainer}>
<Text style={styles.text}>No Internet connection</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
imageContainer: {
flex:1,
justifyContent: 'center',
alignItems: 'center',
marginHorizontal: 20,
},
image: {
width: 160,
height: 220,
alignSelf: 'center',
},
textContainer: {
marginVertical: 15,
},
text: {
fontSize: 20,
}
});
export default NoInternetScreen;
Login.js - which uses NoInternetScreen
import React, {useContext} from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
import {NetworkContext} from '../NetworkContext';
import NoInternetScreen from './NoInternetScreen';
const Login = props => {
const isConnected = useContext(NetworkContext);
return (
isConnected ? <View style={styles.container}>
<Text> Login </Text>
</View> : <NoInternetScreen/>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
}
});
export default Login;
Could you please suggest what could be done to fix it?
Thanks and Regards,
Ankur

React native Drawer only after login

I have snack link here
https://snack.expo.io/#mparvez19861/drawer-navigation?session_id=snack-session-hyLuO4xPa
I am trying to show drawer only if user login, for login there will not be any drawer.
Please help
Thanks
You can accomplish this by wrapping your Drawer Navigator in a Switch Navigator. Upon logging in, the Switch Navigator will switch from the login screen (which is just a screen), to the main App screen (which is initialized with createDrawerNavigator).
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import {
createSwitchNavigator,
createStackNavigator,
createAppContainer,
createDrawerNavigator,
} from 'react-navigation';
class Screen extends Component {
render() {
return (
<View style={styles.container}>
<Text>Screen</Text>
</View>
);
}
}
class AuthScreen extends Component {
render() {
return (
<View style={styles.container}>
<Text>Auth Screen</Text>
<TouchableOpacity onPress={() => this.props.navigation.navigate('App')}>
<Text>Login</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 40,
justifyContent: 'center',
alignItems: 'center',
},
});
const SomeStackNavigator = createStackNavigator({
ScreenA: Screen,
ScreenB: Screen,
});
const AppStack = createDrawerNavigator({
StackA: {
name: 'StackA',
screen: SomeStackNavigator,
},
StackB: {
name: 'StackB',
screen: SomeStackNavigator,
},
});
const AppNavigator = createSwitchNavigator(
{
App: AppStack,
Auth: {
screen: AuthScreen,
},
},
{
initialRouteName: 'Auth',
},
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
Check it out here.

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

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 }

Resources