2

Given some items stored in state, I want to be able to click a button and display a random item from that array. So far it only works on the first click and then it displays the same one letter after the first click.

What exactly is going on?

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      notes: ['hey', 'yo', 'sup'],
      clicked: false
    }
  }

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

  render() {    
    return (
      <div className="App">
        <button onClick={this.handleClick}>Random Note</button>
        <h1>{this.state.clicked ? this.state.notes : ''}</h1>
      </div>
    )
  }
}
3
  • 2
    what did you expect to happen? this.state.notes is an array, but then in your handleClick function you're making notes a string
    – azium
    Apr 7, 2018 at 18:43
  • Cause "h"[0] is "h" ? Apr 7, 2018 at 19:03
  • 1
    You REWRITE notes by one random note. Add one more field f e randomNode: null and write random note in it and display it in render(). Apr 7, 2018 at 19:32

3 Answers 3

2

Add selected note handling

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      notes: ['hey', 'yo', 'sup'],
      selectedNote: null,
      clicked: false
    }
  }

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

  render() {    
    return (
      <div className="App">
        <button onClick={this.handleClick}>Random Note</button>
        <h1>{this.state.clicked && this.state.selectedNote}</h1>
      </div>
    )
  }
}
1

You're overwriting the notes array in state in your handleClick method. Try using a different key (something like activeNote) in handleClick, then use that in your render method rather than this.state.notes.

1
  • Thanks for the reply. I'm not sure what you mean exactly. Could you give me a little code snippet? Apr 7, 2018 at 18:58
0

So I think I solved it.

I ended up adding another state key randomWord and setting it equal to ''.

I then set the state of randomWord to that of this.state.notes when randomized.

Finally, I rendered this.state.randomWord

No clue if that's the correct approach but it's a working solution, lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.