How to add images? (React Native) - javascript

I tried several codes but I only have errors every time.
How to add images from my gallery (no links) one below the other, with text
at the top and bottom of each image?
Like this:
(source: noelshack.com)
import React, { Component } from "react";
import { Text, View, StyleSheet, Image, ImageBackground,ScrollView } from "react-native";
import withBackground from "../components/WithBackground";
class LinksScreen extends Component {
render() {
return (
<ScrollView>
<text>Hi</text>
<Image source={require('./assets/images/ici.jpg')} />
<text> Hello</text>
<text> Hi2</text>
<Image source={require('./assets/images/ici2.jpg')} />
<text> Hello2</text>
</ScrollView>
);
}}
export default withBackground(LinksScreen);
I am novice,
any help would be appreciated.

Can you give a screenshot of the result you are expecting?
There is something called a FlatList you can use that to achieve a list of images.
Note : menuData is an array of objects and Item is an object that has image title and URL
<FlatList
data={this.props.menuData}
renderItem={({ item }) => {
return(
<View style={{ flexDirection: 'row' }}>
<Image source={require(item.imageURL)} />
<Text>{item.imageText}</Text>
</View>
);
}}
keyExtractor={(item) => item.title }
/>
Use this style for Text:
textStyle: {
flex: 1,
width: '100%',
position: 'absolute',
alignSelf: 'center',
backgroundColor: 'rgba(0.57, 0.57, 0.57, 0.3)',
height: '100%',
}

I am going to show you a possibility of working with native-base, but it's just a suggestion. You can see some possibilities in the official docs: https://docs.nativebase.io/Components.html#Components
import React, { Component } from 'react';
import { Image, ImageBackground, View } from 'react-native';
import { Card, CardItem, Text, Left, Right } from 'native-base';
import styles from './styles';
class ProductImage extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<ImageBackground
style={ styles.image }
source={{ uri: this.props.photo }}
>
</ImageBackground>
</View>
);
}
}
export default ProductImage
So if you want to put a photo without props, it's just put the link image, like 'https://www.w3schools.com/w3css/img_lights.jpg'. Don't forget to install the dependence: npm install native-base --save

Can you try this once:
<ScrollView>
<View>
<Text>Hi</Text>
<Image source={require('./assets/snack-icon.png')} style={{ width: '100%',
height: 150, marginBottom: 10, padding: 10 }} resizeMode="cover" />
</View>
<View>
<Text> Hi2</Text>
<Image source={require('./assets/snack-icon.png')} style={{ width: '100%',
height: 150, marginBottom: 10, padding: 10 }} resizeMode="cover" />
<Text> Hello2</Text>
</View>
</ScrollView>

Related

Rendering another screen in react-native app

I'm experiencing trouble navigating between pages in my react native app. When I attempt to use the button, I get the following error message: TypeError: undefined is not an object (evaluating '_this.props.navigation') I have created my app using numerous js files, and id like to navigate between them using buttons. My App.js file renders to the WelcomeScreen from initializing.
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import RecipesList from "cakeapp/app/screens/RecipesList.js";
import { ImageBackground, StyleSheet, View, Text, Button, navigation } from "react-native";
function WelcomeScreen(props) {
return (
<NavigationContainer>
<ImageBackground
style={styles.background}
source={require('cakeapp/app/assets/MainPage.png')}
>
<Text style={styles.text}>MyCakeRecipes</Text>
<View style={styles.homeButton}>
<Button
title="Recipes"
onPress={() => this.props.navigation.navigate('RecipesList')}
/>
</View>
</ImageBackground>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
background: {
flex:1,
justifyContent: "flex-end",
},
text: {
fontSize: 30,
fontWeight: "bold",
color: "white",
textAlign: "center",
bottom: 500,
},
homeButton: {
width: '100%',
height: 40,
backgroundColor: '#5f7f8a'
}
})
export default WelcomeScreen;
import React from 'react';
import { Image, ScrollView, View, Text, } from 'react-native';
const imageDis = {
width: 150,
height: 150
//flex:1,
//justifyContent: "flex-end"
};
const Recipes = () => (
<ScrollView style={{backgroundColor: '#5f7f8a'}}>
<Text style={{ fontSize: 20 }}>Chocolate Cake</Text>
<Image source={require('cakeapp/app/assets/Choc.png')} style={imageDis} />
<Text style={{ fontSize: 20 }}>Chocolate cupcake</Text>
<Image source={require('cakeapp/app/assets/ChocCu.png')} style={imageDis} />
<Text style={{ fontSize: 20 }}>Lemon Cake</Text>
<Image source={require('cakeapp/app/assets/Lemon.png')} style={imageDis} />
<Text style={{ fontSize: 20 }}>Lemom meringue</Text>
<Image source={require('cakeapp/app/assets/LemonM.png')} style={imageDis} />
<Text style={{ fontSize: 20 }}>Chocolate Berry</Text>
<Image source={require('cakeapp/app/assets/ChcoBerry.png')} style={imageDis} />
</ScrollView>
);
export default Recipes
As far as I know, < NavigationContainer> is used in app.js file to define the screens you want to navigate to. And you have to pass navigation as a prop to the component.
Your app.js file should look something like this
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Welcome"
component={WelcomeScreen}
/>
<Stack.Screen
name="Recipes"
component={RecipesList} />
</Stack.Navigator>
</NavigationContainer>
);
};
And your welcomeScreen like this:
const WelcomeScreen = ({ navigation }) => {
return (
<Button
title="RecipesList"
onPress={() =>
navigation.navigate('RecipesList')
}
/>
);
};
Let me know if it doesnt work

Modal won't show the image in react native

I have written a program in which I am showing a list of images in ScrollView when user clicks an image a modal is popped up and image would be shown in large size. But this is not working.
Modal is opening fine but it is not showing the image..
However I have checked the value of image in render method of Modal i.e. ImageViewer, value I am getting is a class object.
App:
import React, {Component} from 'react';
import {View,Modal, ScrollView, Image, TouchableOpacity, StyleSheet} from 'react-native';
import pic1 from './images/sl13.png';
import pic2 from './images/sl14.png';
import pic3 from './images/sl15.png';
import pic4 from './images/sl16.png';
import pic5 from './images/sl17.png';
class App extends Component {
Images = [pic1, pic2, pic3, pic4, pic5];
state = {
modalVisible: false,
}
image = null
close(){
this.setState({modalVisible: false});
}
constructor(props){
super(props);
this.close = this.close.bind(this);
}
showImage(path){
this.image = path;
this.setState({modalVisible: true});
}
render() {
return (
<View style={{alignItems:'center', justifyContent: 'center'}}>
<ScrollView>
{this.Images.map((item)=>{
return (
<TouchableOpacity key={item} onPress={(item)=>this.showImage(item)}>
<View style={{borderColor: 'red', borderWidth: 1, marginBottom: 10}}>
<Image style={{width: 200, height: 200}} source={item} />
</View>
</TouchableOpacity>
)
})}
</ScrollView>
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.image}/>
</View>
);
}
}
Modal:
class ImageViewer extends Component {
render() {
console.log(this.props.image) //Checking Value here
return (
<Modal
style={{top: '50%', left: '50%', transform: 'translate(-50%, -50%) !important'}}
animationType='fade'
transparent={true}
onRequestClose={()=>this.props.closeModal()}
visible={this.props.modalVisible}
>
<View style={{flex:1 ,alignItems: 'center', justifyContent: 'center', backgroundColor:'#00000069'}}>
<View style={{padding:20 , backgroundColor:'#fff', borderRadius: 10}}>
<Image style={{width: 400, height: 600}} source={this.props.image} />
</View>
</View>
</Modal>
)
}
}
export default App;
both are in same file..
Screenshots :
Normal : https://imgur.com/deai02Y.jpg
Clicked on Image: https://imgur.com/POuZlPU.jpg
On Touchableopacity onPress you are actually passing the onPress $event to showImage function instead of item. so correct way of doing it is
<View style={{alignItems:'center', justifyContent: 'center'}}>
<ScrollView>
{this.Images.map((item)=>{
return (
<TouchableOpacity key={item} onPress={()=>this.showImage(item)}>
<View style={{borderColor: 'red', borderWidth: 1, marginBottom: 10}}>
<Image style={{width: 200, height: 200}} source={item} />
</View>
</TouchableOpacity>
)
})}
</ScrollView>
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.image}/>
</View>
after app called write
constructor(props) {
super(props);
this.state = {
image : ''
};
}
and in showImage path
showImage(path){
this.setstate({image : path});
this.setState({modalVisible: true});
}
and in Imageviewer
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.state.image}/>

TypeError: undefined is not an object (evaluating style.width) react native

I just wanted to add an <ImageBackground> to my React Native project, but I always get the error message: "TypeError: undefined is not an object (evaluating style.width)". Error located at ImageBackground (at index.js:31).
I have another project where it works perfectly like this. Could it be a problem of the React Native version?
import React, {Component} from 'react'
import {
StyleSheet,
View,
TouchableOpacity,
Text,
AsyncStorage,
Dimensions,
ImageBackground
} from 'react-native'
import * as Colors from '../../themes/colors'
import {getNavigationOptions} from '../../utils/navigation'
import * as ducks from '../../ducks'
import {connect} from 'react-redux'
class LoginScreen extends Component{
login(){
const {updateCurrentUser} = this.props
updateCurrentUser({name: 'Mauricio'})
console.log('login', this.props.currentUser)
}
olvidarContraseña(){
console.log('olvidar contraseña')
}
render(){
return (
<View style={styles.container}>
<View style={[styles.input, {borderColor: Colors.primary}]}>
<ImageBackground>
style={styles.backgroundImage}
source={require('./trigo_background.jpg')}>
{/* <TouchableOpacity
style={styles.btnSubmit}
onPress={() => this.login()}
>
<Text style={{textAlign: 'center', color: Colors.primary}}>
Iniciar Sesión
</Text>
</TouchableOpacity> */}
</ImageBackground>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
backgroundImage: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
position: 'absolute',
top: 0,
left: 0
},
btnSubmit: {
justifyContent: 'center',
padding: 10,
flexDirection: 'row'
},
input: {
height: 40,
paddingHorizontal: 10,
borderWidth: 1,
borderRadius: 5
}
})
LoginScreen.navigationOptions = ({navigation}) =>
getNavigationOptions('Login', Colors.primary, 'white')
const mapStateToProps = store => ({
currentUser: store.currentUser
})
const mapDispatchToProps = {
updateCurrentUser: ducks.updateCurrentUser
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)
The error is in your code snippet
<ImageBackground> <== Here
style={styles.backgroundImage}
source={require('Valcereal/assets/trigo_background.jpg')}>
{/* <TouchableOpacity
style={styles.btnSubmit}
onPress={() => this.login()}
>
<Text style={{textAlign: 'center', color: Colors.primary}}>
Iniciar Sesión
</Text>
</TouchableOpacity> */}
</ImageBackground>
You've closed the tag and adding lines of code after it which would throw an error since it is not valid jsx
The correct code is
<ImageBackground
style={styles.backgroundImage}
source={require('Valcereal/assets/trigo_background.jpg')}>
{/* <TouchableOpacity
style={styles.btnSubmit}
onPress={() => this.login()}
>
<Text style={{textAlign: 'center', color: Colors.primary}}>
Iniciar Sesión
</Text>
</TouchableOpacity> */}
</ImageBackground>
At the top of your file destructor the height and width property like
const { width, height } = Dimensions.get('window');
In our styles object replace BackgroundImage object with
backgroundImage: {
width: width,
height: height,
position: 'absolute',
top: 0,
left: 0
},
Another alternative to setting a backgroundImage in React native is to set the height and width to 100%.
backgroundImage: {
width: 100%,
height: 100%,
},
Despite the wrong format you have provided, you'll also get the same results/error.
so the style of ImageBackground should be like this:
{ width: undefined, height: undefined }
Provided in the doc's of react-native ImageBackground

How to set background image over view in react native?

I'm trying to set a background image in react native.I want a background cover image. I've done like the below
<ScrollView>
<View>
<Image source={ require('../Images/5.jpg') } style = { styles.image } />
{
this.state.details.map(a =>
<View>
<Text style={ styles.textStyle } > { a.content = a.content.replace(regex, '') } < /Text>
< RadioForm style= {{ width: 350 - 30 }} outerColor = "#080103" innerColor = "#FF5733" itemShowKey = "label" itemRealKey = "item" dataSource = { transform(a.options) } onPress = {(item)=>this._onSelect(item)}/>
</View>)
}
</View>
</ScrollView>
const styles = StyleSheet.create({
image: {
flex: 1,
resizeMode: 'cover',
position: 'absolute',
width: "100%",
flexDirection: 'column'
},
textStyle: {
fontSize: 16,
color: '#000',
padding: 5,
},
});
But I'm getting something like this
You might need to add the ImageBackground outside of your ScrollView and make sure flex is being passed to the ImageBackground style'
For example
<View style={{flex: 1}}>
<ImageBackground
resizeMode={'stretch'} // or cover
style={{flex: 1}} // must be passed from the parent, the number may vary depending upon your screen size
source={require('/*Your Image Path*/')}
>
<ScrollView>
{/*Render the children here*/}
</ScrollView>
</ImageBackground>
</View>
What you need is ImageBackgroundcomponent.
import {ImageBackground} from 'react-native';
<ImageBackground
source={require('./pathToYourImage.png')}
style={yourCustomStyle}>
</ImageBackground>
That should do it.
import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
import { WINDOW } from '../assets/config.js';
class Splash extends React.Component{
render(){
return(
<View style={styles.splashContainer}>
<Image
style={styles.bgImage}
source={require('../assets/images/splash.jpg')}
/>
</View>
)
}
}
const styles = StyleSheet.create({
splashContainer: {
flex: 1
},
bgImage: {
flex: 1,
width: WINDOW.width,
height: WINDOW.height,
}
});
export default Splash;
try like this. This worked fine for me.
Use
<ImageBackground
source={your image path}>

How can I make the custom navigation bar transparent in RNRF

I have tried all the options in react-native-router-flux like: navigationBarStyle or navTransparent and also
navigationBarStyle={[STYLES.navBar]}
all of these are not working while trying to make the custom navigation bar transparent Is there any ways to make it transparent using react-navigation and should I change from react-native-router-flux to react-navigation to do this I have posted it as an issue in Git Hub
here is the link :Github issue #2132
since I found it hard using react-navigation I have switched to RNRF is there any solution to make the custom navBar transparent other than switching from RNRF to RN or is it a bug in RN
here's the code that i use in my NavBar.js file :
import {
View, Image, StatusBar, TouchableWithoutFeedback
} from 'react-native';
import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
class NavBar extends Component {
render() {
return (
<View style={styles.backgroundStyle}>
<StatusBar />
<View style={{ flexDirection: 'row' }}>
<TouchableWithoutFeedback onPress={() => Actions.pop()}>
<Image
source={require('./Images/back-arrow.png')}
style={styles.backarrowStyle} />
</TouchableWithoutFeedback>
<Image
source={require('./Images/help.png')}
style={styles.helpStyle} />
<Image
source={require('./Images/setting.png')}
style={styles.settingStyle} />
</View>
</View>
);
}
}
const styles = {
backgroundStyle: {
backgroundColor: 'transparent',
},
backarrowStyle: {
resizeMode: 'contain',
flexDirection: 'row',
width: 55,
height: 55,
left: 0,
justifyContent: 'flex-start'
},
helpStyle: {
resizeMode: 'contain',
width: 50,
height: 50,
left: 210,
justifyContent: 'flex-end',
position: 'relative'
},
settingStyle: {
resizeMode: 'contain',
width: 50,
height: 50,
justifyContent: 'flex-end',
position: 'relative',
left: 210
}
};
export default NavBar;
and this is my Router.js file:
import React from 'react';
import { Scene, Router } from 'react-native-router-flux';
import MainScreen from './components/MainScreen';
import ChallengeScreen from './components/ChallengeScreen';
import NavBar from './components/NavBar';
import Toss from './components/Toss';
const RouterComponent = () => {
return (
<Router>
<Scene key="root">
<Scene key="homeScreen" component={MainScreen} hideNavBar={1} />
<Scene
key="screen2" component={ChallengeScreen}
navBar={NavBar}
/>
<Scene
key="screen3" component={Toss}
navBar={NavBar}
/>
</Scene>
</Router>
);
};
export default RouterComponent;
What you can do is set semi-transparent navbar by setting navbar opacity in navigationBarStyle
<Scene key="scene2" component={ChallengeScreen}
navigationBarStyle={{opacity:0.3}}/>
but the problem is the whole navbar including left and right button will be inherit the opacity. I recommend just set hidenavbar={true} and implement custom navbar in the scene component. For eg: in Scene2 component (ChallengeScreen)
render() {
const customNavbar = {
<View style={{position:'absolute', top:0, flexDirection:'row', justifyContent:'space-between', backgroundColor:'transparent', padding:10}}>
<TouchableOpacity>
<Text>Left Button</Text>
</TouchableOpacity>
<Text>Title</Text>
<TouchableOpacity>
<Text>Right Button</Text>
</TouchableOpacity>
</View>
}
return () {
<View style={{flex:1}}>
{customNavbar}
<View></View>
</View>
}
}

Categories

Resources