onChange the textbox value is not updating in HTML form using React

Viewed 2422

Username and Password change event is getting called but its not appearing in the UI text box. Here is the code:

class Login extends Component{
constructor(props){
    super(props)
    this.state= {
        username: 'username',
        password: 'password'
    }

}

handleUsernameChange = (event) => {
    console.log(event.target.value);
    this.setState = ({
        username: event.target.value
    });
}

handlePasswordChange = (event) => {
    this.setState = ({
        password: event.target.value
    })
}

render(){
    return(
        <div>
            User Name: <input type="text" name="username" value={this.state.username} onChange={this.handleUsernameChange}></input>
            Password: <input type="password" name="password" value={this.state.username} onChange={this.handlePasswordChange} />
            <button>Login</button>
        </div>
    )
}
}
export default Login

Console is logging the updated username but I am not able to see it in UI. Let me know if I am missing something. Thanks in advance.

2 Answers

Ok, so you are having a couple of issues here. The first one is that you are calling 'this.state' method incorrectly by trying to assign it to some value. So you should change this.setState = ({}) to this.setState({}).

The second one is that you are assigning the value of this.state.username twice to both inputs instead of assigning the correct value to the corresponding input.

The last error, and this one is the tricky one, is that you are assigning a function to the onChange event incorrectly. If the function you assign doesn't have any reference to the class object instance, it would be ok. But as your function has a reference to the instance (the reference is the keyword 'this' that references the instance of the class that's calling the function) you need to bind the function to the object, so that when the function is called, the 'this' keyword knows which object you want to change the state to. So you have to change onChange={this.handleUsernameChange} to onChange={this.handleUsernameChange.bind(this)}

Change this.setState = ({ to this.setState({

this.setState({
    username: event.target.value
})

And change password input value from value={this.state.username} to value={this.state.password}

Related