Reputation: 57
I want to change my background image when i submit the city name , but don't know how to change the background image dynamically..i have been using a ternary operator but is not giving me the desired output.(React-native noobie)
Here is my main code..
import React, {Component} from 'react';
import {Image, TextInput, ImageBackground, StyleSheet, Text, View} from 'react-native';
import OpenWeatherMap from './Components/openweathermap';
import WeatherForecast from './Components/forecast';
import Images from './android/app/assets/images';
export default class why extends Component {
constructor(props){
super(props);
this.state = {forecast: null, doesShow: false};
}
textHandleChange = event => {
let city = event.nativeEvent.text;
OpenWeatherMap.fetchWeather(city).then(forecast =>{
this.setState({forecast : forecast}); //Used for fetching weather data using fetchAPI
});
}
backgroundChange = () => {
this.setState({doesShow:true})
}
render(){
let content = null;
if(this.state.forecast !== null){
content = (
<WeatherForecast
main = {this.state.forecast.main}
description = {this.state.forecast.description}
temp = {this.state.forecast.temp} //For displaying the fetched Weather data
/>
);
}
return(
{ {this.state.doesShow} === true ?
<ImageBackground
source = {Images.pic4}
style={styles.imageDeco}> :
<ImageBackground
source = {Images.pic3}
style={styles.imageDeco}> }
<View style= {styles.a1}>
<View style = {styles.top}>
<Text style={styles.a2}>Weather Forecast</Text>
</View>
<Text style={styles.a3}>Enter your city ID</Text>
<TextInput
onSubmitEditing={this.textHandleChange}
onChangeText={this.backgroundChange}
style={styles.a4}></TextInput>
{content}
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
imageDeco:{
flex:1,
width: '100%',
height: '100%'
},
a1:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(47,163,218,0.2)'
},
a2:{
fontSize: 30,
color: 'rgba(128,0,0,1)',
borderColor: '#FFF',
borderWidth: 2,
backgroundColor: 'rgba(255,219,153,0.6)',
padding: 10,
paddingLeft: 10,
paddingRight: 10,
fontFamily: 'Lobster'
},
a3:{
fontSize: 25,
color: 'blue',
fontFamily: 'Pacifico'
},
a4:{
backgroundColor:'#ffe0bd',
width: '30%',
marginTop: 20,
borderColor: 'black',
borderRadius: 50,
fontFamily: 'Lobster',
fontSize: 30,
},
top:{
justifyContent:'center',
alignItems:'center',
width: '70%'
}
})
My main aim is to change the background image from the fetched weather data.
Upvotes: 4
Views: 3255
Reputation: 1894
var icon = this.props.img1 ? require('image/img1.png') : require('image/img2.png');
<Image source={icon} />
you can change the logic here as you want, using switch
or build the require..as you want.
And use the background img via nesting form react-native. I do this all the time. You can find details here: https://facebook.github.io/react-native/docs/images#background-image-via-nesting
Upvotes: 2