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

168
Vistas
Change input.value from onchange function (Reactjs)

I have an input tied to the state. HD variable. But I want to add validation so that if a negative number is entered, onblur the value of the input is set to the previous value of HD.

I just don't know how to call the input and make it change its value. I tried to ref it here for an uncontrolled attempt at changing it (https://www.pluralsight.com/guides/how-to-use-react-to-set-the-value-of-an-input)

Render

 <input
                      className="input"
                      name="HDin"
                      type="number"
                      defaultValue={this.state.HD}
                      onBlur={this.changeHD}
                      ref={this.HDref}
                    ></input>
changeHD = (e) => {
    let temp = this.state.HD;
    const amnt = e.target;
    let o = 0;
    o = parseInt(e.target.value);
    console.log(o);
    if (o < 0 || o === "" || o == NaN) {
      this.setState({ HD: temp });
      this.HDref.value = temp;
      this.setState({[e.target.value]: temp});
    } else {
      this.setState({ HD: o });
    }
  };

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

input value={this.state} then you can change it using this.setstate

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use setState and the prevState which is available.

class Counter extends React.Component {
  state = {
    counter: 0
  };
  onChangeHandler = (e) => {
    const currentValue = e.target.value;

    if (currentValue <= -1) {
      this.setState((prevState, props) => {
        return { counter: prevState.counter };
      });
    } else {
      this.setState({
        counter: currentValue
      });
    }
  };

  render() {
    return (
      <div>
        {this.state.counter}
        <input type="text" onBlur={this.onChangeHandler} />
      </div>
    );
  }
}
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