Maarek Sillamäe
Maarek Sillamäe

Reputation: 13

react native random background image

I am learning react native at the moment, I got my random background image to work but there is a bug now and I have no idea how to fix it easily, it now changes background everytime I do anything in app. Main idea was to change image if app opens I added video what seems to be problem at the moment. Somehow background is not changeing when I update my task.

https://www.youtube.com/watch?v=JkAfe6BDZYg&feature=youtu.be&ab_channel=TheMrMaarek

    const { height, width } = Dimensions.get("window");
const randomImages = [
  require('./images/talv.jpg'),
  require('./images/kevad.jpg'),
  require('./images/suvi.jpg'),
  require('./images/sügis.jpg'),
];

export default class App extends React.Component {
  state = {
    newToDo: "",
    loadedToDos: false,
    toDos: {}
  };

  componentDidMount = () => {
    this._loadedToDos();
  };

  render() {
    const { newToDo, loadedToDos, toDos } = this.state;
    console.log(toDos);
    if (!loadedToDos) {
      return <AppLoading />;
    }
    
    return (
      <ImageBackground source={randomImages[Math.floor(Math.random()*randomImages.length)]} style={styles.container}>
        <StatusBar barStyle="light-content" />
        <Text style={styles.title}>MS ToDo App</Text>
        
        <View style={styles.card}>
          <TextInput
            style={styles.input}
            placeholder={"Add new task here..."}
            value={newToDo}
            onChangeText={this._controlNewToDo}
            placeholderTextColor={"black"}
            returnKeyType={"done"}
            autoCorrect={false}
            onSubmitEditing={this._addToDo}
            underlineColorAndroid={"transparent"}
          />
          <ScrollView contentContainerStyle={styles.toDos}>
            {Object.values(toDos)
              .sort((a, b) => {
                return a.createdAt - b.createdAt;
              })
              .map(toDo => (
                <ToDo
                  key={toDo.id}
                  deleteToDo={this._deleteToDo}
                  uncompleteToDo={this._uncompleteToDo}
                  completeToDo={this._completeToDo}
                  updateToDo={this._updateToDo}
                  {...toDo}
                />
              ))}
          </ScrollView>
        </View>
      </ImageBackground>

Upvotes: 1

Views: 543

Answers (1)

Wen W
Wen W

Reputation: 2647

you want to just randomize the image in componentDidMount,

state = {
    newToDo: "",
    loadedToDos: false,
    toDos: {},
    currentImage: null,
  };
...
componentDidMount = () => {
    this._loadedToDos();
    this.currentImage = randomImages[Math.floor(Math.random()*randomImages.length)];
  };

...
<ImageBackground source={this.currentImage} style={styles.container}>

Upvotes: 1

Related Questions