Niru
Niru

Reputation: 1547

React Input event.target.value does not match actual input value

I have a HtmlInputElement that I define a onKeyDown handler on like so:

const keyDownHandler = (event: React.KeyboardEvent<HTMLInputElement>) => {
    console.log("The event target: ", event.target);
    console.log("The event target value: ", event.target.value);
    if(event.key === ...) {
        if(textValue.length === 0) {
              event.preventDefault();
              //Do other things.
        }
        ....
    }
};

I notice that if I type some input into the input box such as asd, I'll get the following outputs:

The event target:
    <input ... value="asd">

The target value: as

It seems my target value on the second print is always 1 input behind, and I don't see why its not returning my actual value.

I also define a onChange handler that triggers after my other on key down handler. After reading MDN I thought that the event.target.value would return the parametrized HTMLInputElement and its actual value, but it doesn't seem to.

Is there some other attribute I should be accessing in order to get the new computed value after the key press?

To add to this, I am trying to emulate backspace behavior in my jest test using testing-library.

I do this with userEvent.type(myInputBox, '{Backspace}');. In the browser I notice that my onChange handler is invoked, but not in jest test. I am trying to emulate this behavior because on the key down event I am not preventing default, and I want the default behavior to occur if the input box is not empty, otherwise do another action. In browsers, the default behavior occurs, but not in the test and I am not sure what is missing.

Upvotes: 1

Views: 1845

Answers (1)

Dostonbek Oripjonov
Dostonbek Oripjonov

Reputation: 1674

I think you should try keyup or keypress methods.

  • KeyDown – when a key was pushed down
  • KeyUp – when a pushed button was released, and after the value of input/textarea is updated (the only one among these)
  • KeyPress – between those and doesn't actually mean a key was pushed and released.

Upvotes: 2

Related Questions