Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native using state in image require

Why I can´t use states in my image

<Image source={require(this.state.image)} style={styles.img} /> 

I would like to change the image, getting it from an array when I click in the button a raffle function changes the image state, everything is working, but I can´t pass a state as a required parameter, how to solve it?

import React, {Component} from 'react';
import {
  Platform, 
  StyleSheet, 
  Text, 
  View,
  Image
} from 'react-native';
import Button from './src/components/Button.js';

export default class App extends Component{

  constructor(props){
    super(props);

    this.state = {
      image: './src/assets/interrogacao.png',
    }

    this.imagesArray = [
      './src/assets/1.jpg',
      './src/assets/2.jpg',
      './src/assets/3.jpg',
    ]

    this.rafflePosition = this.rafflePosition.bind(this);

  }

  rafflePosition(){
    let state = this.state;
    let numRandom = Math.floor(Math.random() * this.imagesArray.length)
    this.state.image = this.imagesArray[numRandom];
    var teste = this.state.image;
    this.setState(state);
    alert('teste' + teste)
  }

  render() {
    return (
      <View style={styles.container}> 
        <Image source={require(this.state.image)} style={styles.img} />
        <Button onPress={this.rafflePosition} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  img: {
    width: 220,
    height: 220,
    marginBottom: 90
  }

});
like image 502
Vitor Augusto Batista Rocha Avatar asked Feb 11 '26 17:02

Vitor Augusto Batista Rocha


1 Answers

require uses static urls only. Therefore, a variable used in place of the static url will not work. Because, require checks for the image file's existence before bundling the app, which happens even before rendering the variable itself.

So, you need to require the images beforehand in variables and then assign the variables, having the already required images in them, to the source like this:

const image = require('path_to_image.png')

<Image source={image} />
like image 139
Noor Jahan Mukammel Avatar answered Feb 15 '26 06:02

Noor Jahan Mukammel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!