The input value in a React controlled form is insensible to keystrokes

The input value doesn’t seem to be following the state

I’m keeping the input value in a state, but setState doesn’t seem to be updating the value, which makes the input insensible to keystrokes

I coded a simplified form that has the exact issue

Here’s the code:

import React, { Component } from 'react'
import style from "./Prueba.module.css";

export default class Prueba extends Component {
constructor() {
    super()
    this.state = {
        email: '',
        emailError: ''
    }
}

validate(inputStr) {
    let error = '';
    if (!inputStr) {
        error =  'email is required'
    } else 
        if (!inputStr.match(/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/)) {
            error = 'email is invalid';
        }
    return error
}

handleInputChange(e) {
    this.setState({
        ...this.state, 
        [e.target.name]: e.target.value
    })

    let emailErr = this.validate(e.target.value)
    if (emailErr) 
        this.setState({
            ...this.state,
            emailError: emailErr
        });
}

render() {
    return (
        <div>
            <form>
                <input className={this.state.emailError && style.red}
                    type="text" 
                    name="email" 
                    value={this.state.email} 
                    onChange={this.handleInputChange.bind(this)} 
                    />
            </form>
        </div>
    )
}

}

When I comment the validation part in the handleInputChange handler, the input starts behaving correctly, but I noted that the state never includes the last character

What am I doing wrong?

Rafael

1 thought on “The input value in a React controlled form is insensible to keystrokes”

  1. I replaced the input handler by

    handleInputChange(e) {
    
        let emailErr = this.validate(e.target.value)
        this.setState({
            ...this.state,
            [e.target.name]: e.target.value,
            emailError: emailErr
        })
    }
    

    and it worked fine

    Reply

Leave a Comment