How to set background image over view in react native? - javascript

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

Related

React Native change background color on container view doesn't work

I am new to react native. I tried to change the background view on the container seems like it doesn't work. I attached the codes below.
Could anyone here tell me what is wrong with the code below?
const HomeScreen = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: '#FF0000' }}>
<Text style={{
color: COLORS.Text,
marginLeft: 14,
marginTop: 16,
width: 100,
height: 20
}}>Hello world</Text>
</View>
</SafeAreaView>
);
Check the below code:
import React from 'react';
import {StyleSheet, Text, SafeAreaView } from 'react-native';
const App = () => {
return (
<SafeAreaView style={styles.container}>
<Text style={styles.text}>Page content</Text>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'green'
},
text: {
fontSize: 25,
fontWeight: '500',
},
});
export default App;
For more information, you can explore SafeArea Documentation.

How to overlap other controls when changing height trough animation?

I wanto to overlap other controls when changing the height of an other control. It should be something like when you pull up a view.
I created a little example:
And when i press on the blue button it goes up:
But the other controls just get smaler. I would like to "overlap" so that the red box would be not visible anymore, only after i make the blue box smal again.
Thats the Code:
import React, { Component } from 'react';
import { Animated, TouchableOpacity, Text, View, StyleSheet } from 'react-native';
export const IMAGE_HEIGHT = 50;
export const IMAGE_HEIGHT_SMALL = 500;
export default class App extends Component {
constructor(props) {
super(props)
this.moveAnimation = new Animated.Value(50)
}
_changeHeight = () => {
Animated.spring(this.moveAnimation, {
duration: 50,
toValue:IMAGE_HEIGHT_SMALL,
}).start()
}
render() {
return (
<View style={styles.container}>
<View style={{flex:1, backgroundColor:'red', alignSelf: 'stretch'}}>
<View style={{flex:1, backgroundColor:'yellow'}}>
<Text>Das ist einer Text in gelb</Text>
</View>
<View style={{flex:1, backgroundColor:'red'}}>
<Text>Das ist einer Text in rot</Text>
</View>
</View>
<Animated.View style={[styles.panel, {height:this.moveAnimation}]}>
<TouchableOpacity style={styles.loginButton} onPress={this._changeHeight}>
<Text style={{textAlign:'center'}}>Login</Text>
</TouchableOpacity>
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
panel:{
height:50,
justifyContent :'flex-end',
backgroundColor:'blue',
alignSelf: 'stretch'
},
loginButton: {
backgroundColor: '#2980b9',
flex:1
},
});
Found it, there is position:'absolute'

How to add images? (React Native)

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>

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

Make view 80% width of parent in React Native

I'm creating a form in React Native and would like to make my TextInputs 80% of the screen width.
With HTML and ordinary CSS, this would be straightforward:
input {
display: block;
width: 80%;
margin: auto;
}
Except that React Native doesn't support the display property, percentage widths, or auto margins.
So what should I do instead? There's some discussion of this problem in React Native's issue tracker, but the proposed solutions seem like nasty hacks.
As of React Native 0.42 height: and width: accept percentages.
Use width: 80% in your stylesheets and it just works.
Screenshot
Live Example
Child Width/Height as Proportion of Parent
Code
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
const width_proportion = '80%';
const height_proportion = '40%';
const styles = StyleSheet.create({
screen: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#5A9BD4',
},
box: {
width: width_proportion,
height: height_proportion,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#B8D2EC',
},
text: {
fontSize: 18,
},
});
export default () => (
<View style={styles.screen}>
<View style={styles.box}>
<Text style={styles.text}>
{width_proportion} of width{'\n'}
{height_proportion} of height
</Text>
</View>
</View>
);
That should fit your needs:
var yourComponent = React.createClass({
render: function () {
return (
<View style={{flex:1, flexDirection:'column', justifyContent:'center'}}>
<View style={{flexDirection:'row'}}>
<TextInput style={{flex:0.8, borderWidth:1, height:20}}></TextInput>
<View style={{flex:0.2}}></View> // spacer
</View>
</View>
);
}
});
If you are simply looking to make the input relative to the screen width, an easy way would be to use Dimensions:
// De structure Dimensions from React
var React = require('react-native');
var {
...
Dimensions
} = React;
// Store width in variable
var width = Dimensions.get('window').width;
// Use width variable in style declaration
<TextInput style={{ width: width * .8 }} />
I've set up a working project here. Code is also below.
https://rnplay.org/apps/rqQPCQ
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
Dimensions
} = React;
var width = Dimensions.get('window').width;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={{fontSize:22}}>Percentage Width In React Native</Text>
<View style={{marginTop:100, flexDirection: 'row',justifyContent: 'center'}}>
<TextInput style={{backgroundColor: '#dddddd', height: 60, width: width*.8 }} />
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:100
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
In your StyleSheet, simply put:
width: '80%';
instead of:
width: 80%;
Keep Coding........ :)
You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:
import EStyleSheet from 'react-native-extended-stylesheet';
const styles = EStyleSheet.create({
column: {
width: '80%',
height: '50%',
marginLeft: '10%'
}
});
The technique I use for having percentage width of the parent is adding an extra spacer view in combination with some flexbox. This will not apply to all scenarios but it can be very helpful.
So here we go:
class PercentageWidth extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.percentageWidthView}>
{/* Some content */}
</View>
<View style={styles.spacer}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row'
},
percentageWidthView: {
flex: 60
},
spacer: {
flex: 40
}
});
Basically the flex property is the width relative to the "total" flex of all items in the flex container. So if all items sum to 100 you have a percentage. In the example I could have used flex values 6 & 4 for the same result, so it's even more FLEXible.
If you want to center the percentage width view: add two spacers with half the width. So in the example it would be 2-6-2.
Of course adding the extra views is not the nicest thing in the world, but in a real world app I can image the spacer will contain different content.
I have an updated solution (late 2019) , to get 80% width of parent Responsively with Hooks it work's even if the device rotate.
You can use Dimensions.get('window').width to get Device Width in this example you can see how you can do it Responsively
import React, { useEffect, useState } from 'react';
import { Dimensions , View , Text , StyleSheet } from 'react-native';
export default const AwesomeProject() => {
const [screenData, setScreenData] = useState(Dimensions.get('window').width);
useEffect(() => {
const onChange = () => {
setScreenData(Dimensions.get('window').width);
};
Dimensions.addEventListener('change', onChange);
return () => {Dimensions.removeEventListener('change', onChange);};
});
return (
<View style={[styles.container, { width: screenData * 0.8 }]}>
<Text> I'mAwesome </Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#eee',
},
});
The easiest way to achieve is by applying width to view.
width: '80%'
This is the way I got the solution. Simple and Sweet. Independent of Screen density:
export default class AwesomeProject extends Component {
constructor(props){
super(props);
this.state = {text: ""}
}
render() {
return (
<View
style={{
flex: 1,
backgroundColor: "#ececec",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}
>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 1"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 2"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<Button
onPress={onButtonPress}
title="Press Me"
accessibilityLabel="See an Information"
/>
</View>
</View>
);
}
}
Just add quotes around the size in your code. Using this you can use percentage in width, height
input: {
width: '80%'
}

Categories

Resources