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 Commented Apr 7, 2018 at 18:43
  • Cause "h"[0] is "h" ? Commented 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(). Commented 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>
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Thanks for the reply. I'm not sure what you mean exactly. Could you give me a little code snippet?
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.

Comments

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.