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

177
Visualizações
React - How can i add new value to an array and display this array in alert window?

I am writing a really simple program but I have got a small problem. When I write a new omen in input label, I want to add this to the array that is in state and display whole content of the array in alert box. How can I do it in the easiest way?

class Draw extends React.Component {
  state = {
    omen: "",
    omens: ["first", "second", "third"],
    newOmen: "",
  };

  handleRandomOmen = () => {
    const omensArray = this.state.omens;
    const randomOmen =
      omensArray[Math.floor(Math.random() * omensArray.length)];

    this.setState({
      omen: randomOmen,
    });
  };

  handleChange = (e) => {
    this.setState({
      newOmen: e.target.value,
    });
  };

  handleAddOmen = () => {
    const test = this.state.omens.push(this.state.newOmen);
    console.log(test);
  };

  render() {
    return (
      <div className="app">
        <button onClick={this.handleRandomOmen}>Show omen</button>
        <br />
        <input
          type="text"
          value={this.state.newOmen}
          onChange={this.handleChange}
        />
        <button onClick={this.handleAddOmen}>Add omen</button>
        <h1>{this.state.omen}</h1>
      </div>
    );
  }
}

ReactDOM.render(<Draw />, document.getElementById("root"));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you always need to update a state with setState, adding a new array value with push will be overriden by the next react cycle.

You can use your the spread syntax to create a new array with the old values + your new one:

  handleAddOmen = () => {
    this.setState({
        omens: [
            ...this.state.omens,
            this.state.newOmen
        ]
    });
  };
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