0

I'm trying to render a random array item from state so that (e.g - [0] might change to [2] on reload.]

Here is what I tried so far, any tips or ideas please?

here is my state:

     state = {
      randomItem: ['one', 'two', 'three', 'four'],
    },
    selected: null,
    clicked: false,
  };

here is my handleClick function which will randomise the items grabbed from array

  handleClick = () => {
    this.setState({
      clicked: true,
      selected: this.state.randomItem.selected[
        Math.floor(Math.random() * this.state.selected.length)
      ],
    });
  };

here is how im trying to return it

         <View>
            <TouchableOpacity onPress={this.handleClick}>
              <Text>{this.state.clicked && this.state.selected}</Text>
            </TouchableOpacity>
          </View>
3
  • Are selected and clicked part of your state? They don't look like they are from your snippet. Mind sharing the entire component? Commented Jan 17, 2020 at 1:44
  • Where's the state randomStatus.demand? Commented Jan 17, 2020 at 1:54
  • sorry guys, that was typos! Might bad. Commented Jan 17, 2020 at 2:31

1 Answer 1

3

I believe you meant to say randomItem instead of randomStatus in handleClick().

Try changing handleClick() like so:

    handleClick = () => {
    this.setState(prev => ({
      ...prev,
      clicked: true,
      selected:
        prev.randomItem[Math.floor(Math.random() * prev.randomItem.length) + 0]
    }));
  };

Also, I think your state has a typo as well. It should be:

    state = {
    randomItem: ["one", "two", "three", "four"],
    selected: null,
    clicked: false
  };
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thank you! Now, another question. Is it possible to use the same handleClick to have two different outputs? e.g one text might render "One" and another Text might render "Four" Or will I need to modify or have a separate script to achieve that
Add selected1 and selected2 to state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.