How to change image when a button is clicked on Expo?


I am trying to make an app that shows cat pictures on Expo. I have a cat picture that is displayed originally. I have a button and when I click the button, I want to change the cat picture that is displayed. Here is what I have:

let imageUri = {uri:  'https://images.unsplash.com/photo-1615789591457-74a63395c990?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8ZG9tZXN0aWMlMjBjYXR8ZW58MHx8MHx8&w=1000&q=80'};

I define a function that changes the imageUri value:

const displayImage = async () => {
  imageUri = {uri: 'https://images.unsplash.com/photo-1529778873920-4da4926a72c2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Y3V0ZSUyMGNhdHxlbnwwfHwwfHw%3D&w=1000&q=80'}
}

Then inside of return() I do the following:

    <View style={styles.container}>
      <ImageBackground
        source={require('./assets/images/background.png')}
        style={styles.image}
        />
        <Text style={styles.text}> Here is a cat picture </Text>
        <Button
          style = {styles.button}
          title="Display"
          onPress = {() => displayImage()}
        />
        <Image source={imageUri} style = {{width: 155, height: 259}} />
    </View>

However, it does not update the picture.

Source: React – Stack Overflow

November 28, 2021
Category : News
Tags: expo | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.