javascriptreactjsevent-handlingicallbackeventhandler

React Js - Unable to enter value in Input Field


I appreciate all of your idea in advance. My problem here is the input field of the email is not updating. Can anyone give me a solution?

<input
    type="text"
    placeholder="Enter Email "
    onChange={this.emailHandle}
    value={this.state.email}
/>

Event handler for the above input field is here:

emailHandle = (e) => {
    if (e.target.value !== "undefined") {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (pattern.test(e.target.value)) {
            console.log(e.target.value);
            this.setState({ email: e.target.value })
        }
    }
}

Solution

  • What's the initial value of your component state? For one, if you're not initializing the email property on state to be an empty string, and it's undefined, you're blocking that state from ever updating with your undefined check. But you have a bigger problem than that. You're testing to see if the value of the input matches your email regex pattern. That won't ever work if you use that check to block setting state. onChange is going to fire every time the input value changes, and that means it's going to change one character at a time. So what's happening is the user types a character, the onChange fires, but it doesn't match your pattern, and you don't update state.

    What you want to do is always update state and then handle this as validation to block submitting the form. Or you could show an error of some kind, but you need to always call setState with the new value on e.target.value.