Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all articles
Browse latest Browse all 16552

Image won't update when looped

$
0
0

I'm quite new to the whole React Native and JS stuff so I might be making a silly mistake here. I have the following code that I got from here: https://reactnativecode.com/change-image-source-dynamically/

The code is a little bit adjusted as I want it to loop.

The problem is as follows: It changes the first time. Then when clicked again it changes the URL (as I have it in a Text component) but the image doesn't show up again. Then when pressed again (3th time) the Text (variable name) won't change anymore and the image will still not show up.

import React, { Component } from 'react';

import { StyleSheet, View, Text, Image, Button, Platform, TouchableHighlight } from 'react-native';

export default class App extends Component {

  constructor() {
    super();
    this.state = {
      imageURL: 'https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg'
    }
  }

  Load_New_Image = () => {
    if (this.state.imageURL == 'https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg'){
      this.setState({
        imageURL: 'https://reactnativecode.com/wp-content/uploads/2018/02/motorcycle.jpg'
      })
    }else{
      this.setState({
        imageURL: 'https://reactnativecode.com/wp-content/uploads/2018/02/Guitar.jpg'
      })
    }
  }

  render() {
    console.log('source: ', this.state.imageURL)
    return (
      <View style={styles.MainContainer}>
        <TouchableHighlight onPress={this.Load_New_Image}>
        <Image
          key={this.state.imageURL}
          source={{ uri: this.state.imageURL }}
          style={styles.imageStyle} />
        </TouchableHighlight>

        <Text>{this.state.imageURL}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({

  MainContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
    paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
    margin: 10
  },

  imageStyle: {
    width: 200,
    height: 300,
    resizeMode: 'center'

  }

});

Viewing all articles
Browse latest Browse all 16552

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>