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

171
Vistas
setState not working properly when using value={} in input field

I am using React JS. I am setting the state, however, there is a problem, in the value={} part of the input field.

Here is my code:

import React from 'react';



class SomeClass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passCode: {
                email: "Email",
                password: "Password"
            },
            errorMessage: ''
        };
    }



    handleChange = (event) =>{
        console.log(`input detected`);
        let request = Object.assign({},this.state.passCode);
        request.email = event.target.value;
        request.password = event.target.value;
        this.setState({passCode: request});
     }


    
    
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                
                    <label>Email Address</label>
                    <input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" />
  
                    <label>Password</label>   
                    <input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" />

                <Button type="submit">
                    Sign In</Button>
            </form>
        );
    }
    
}


export default SomeClass;

My Question:

I have is for the value attribute of the input fields, I think setState is not working properly:

In the passCode object of the state. When I type the email, both fields get set to what I typed in the email field. When I type the password, both fields get set to what I typed in the password field.

What's the reason for such problem?

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

0

setState is working properly; your handleChange isn't. You're setting both email and password to the value of the input regardless of which input the change occurred on. Instead, you want to update just the relevant property. To do that, I'd add name attributes to the input elements (name="email" and name="password"), then:

handleChange = ({currentTarget: {name, value}}) =>{
    console.log(`input detected`);
    this.setState(({passCode}) => {
        return {passCode: {...passCode, [name]: value}};
    });
};

Key bits there are:

  • It only updates the property the change related to, keeping the other one unchanged, by using the name of the input.
  • It uses the callback version of setState (best practice since we're setting state based on existing state).
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your funtion handleChange is wrong. You should update like this with using name:

handleChange = (event) => {
  console.log(`input detected`);
  const { name, value } = event.target;
  this.setState({ passCode: { ...this.state.passCode, [name]: value } });
};

And set name to input:

<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" name="email" />
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password" />
about 4 years ago · Juan Pablo Isaza Denunciar

0

The methods they gaved are good, but I still suggest that you separate the methods of changing the two, maybe it will be much better.

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