Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Display a random item from a collection in state is not working

I am trying to have it so when a person clicks on the Your Fortune button, a random fortune appears. Instead the fortunes just all show up and the onClick does not work as intended. I am confused as to where I might have messed up. Any help is appreciated.

import React from "react";
import {Link} from "react-router-dom"

class Fortune extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        fortunes: [
            "An exciting opporunity lies ahead",
            "A long time friend will brirng wise advice in the coming week",
            "You will find great fortunes in unexpected places",
            "Never give up... Unless you want to thats cool too",
            "111",
            "222",
            "333",
            "444",
            "Maybe a nap is what you need",
            "Don't Text Your EX!"
        ],
        fortune: ""
    }
}

componentDidMount() {
    this.getFortune();
}

getFortune = () =>  {
    let rand = Math.floor(Math.random() * (this.state.fortunes.length) + 0)
    console.log(rand);
    this.setState({
        fortune: this.state.fortunes[rand]
    })
}



render() {
    return (
        <body>
        <div className="home-buttons-wrapper">
            
            <button onClick={Fortune.getFortune}>Your Fortune</button>
            <h5>{this.state.fortunes}</h5>
            
        </div>
        </body>
    )
}
}

console.log('getFortune');

export default Fortune; 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

onClick={Fortune.getFortune}

should be:

onClick={this.getFortune}

and

<h5>{this.state.fortunes}</h5>

should be without trailing 's' (that's why you see the entire collection)

<h5>{this.state.fortune}</h5>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda