React - accessing specific index of array in state with a variable

I am trying to complete the Random Quote Generator, by creating a random index stored in a variable. The variable is updated with a new random number on load or when a button is pressed. I wrote it as I would in JavaScript, but it is not working. Why can’t React read this variable?

  render() {
    let randomNumber = Math.floor(Math.random() * 4) + 1;
    return (
      <div>
        <h1 id="text">"{this.state.list[randomNumber].quote}"</h1>
        <h2 id="author">- {this.state.list[randomNumber].author}</h2>
      </div>
    );
  }

–codesandbox.io/s/ywrnqwzrvv–

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36.

You should do it more react way.

You can add an event listener called onClick to the button and call a function which will update the quote. https://reactjs.org/docs/handling-events.html

Then in your function you can update your randomNumber.

It can read it, and it’s working exactly the same way it would in any JS file (or any programming language for that matter).

  1. randomNumber is a number between 1 and 4 inclusive.
  2. You use that number.

I know what you’ve done wrong, but I would like to know your thinking here: how do you think the code you currently have can ever update without refreshing the screen (which reliably runs all the code again, so new random value, so maybe new quote)?

Got it, I moved the logic to its own method, got it to update correctly, and also managed to get the first quote to be random.
Is there a better, 100% predictable way to make sure I don’t get the same quote twice, which just looks like the page didn’t respond to the click.

  componentWillMount = () => {
    this.getRandomNumber();
  };
  getRandomNumber = e => {
    let random = Math.floor(Math.random() * 6);
    if (this.state.randomNumber === random) {
      random = Math.floor(Math.random() * 6);
    }
    this.setState({
      randomNumber: random
    });
  };
  render() {
    return (
      <div>
        <h1 id="text">"{this.state.list[this.state.randomNumber].quote}"</h1>
        <h2 id="author">- {this.state.list[this.state.randomNumber].author}</h2>
        <button id="new-quote" onClick={this.getRandomNumber}>
          New Quote
        </button>
        <button id="tweet-quote" href="twitter.com/intent/tweet">
          <i className="fab fa-twitter" />
        </button>
      </div>
    );
  }
}
1 Like