Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda