blankface
blankface

Reputation: 6347

Input type number not updating value on enter

App holds an input element that updates on enter, on blur and on the next button click. When I inspect the element in dev tools, the value attribute updates on both blur and next button click, but never on the enter.

import * as React from "react";
import { render } from "react-dom";

interface IAppProps {
  InputVal: number;
  onEnter: (num: number) => void;
}

const Parent: React.FC = () => {
  const [currentValue, setCurrentValue] = React.useState(1);
  const grabVal = (val: number) => {
    console.log("New value::", val);
    setCurrentValue(val);
  };

  return <App InputVal={currentValue} onEnter={grabVal} />;
};

const App: React.FC<IAppProps> = ({ InputVal, onEnter }) => {
  const inputRef: any = React.createRef();
  const handleEnterKey = (e: any) => {
    if (e.keyCode === 13) {
      onEnter(Number((e.target as HTMLInputElement).value));
    }
  };

  const nextClick = (e: any) => {
    inputRef.current.value = InputVal + 1;
    onEnter(InputVal + 1);
  };

  const blurry = (e: any) => {
    onEnter(Number(e.target.value));
  };

  return (
    <>
      <input
        type="number"
        onKeyUp={handleEnterKey}
        ref={inputRef}
        defaultValue={InputVal as any}
        onBlur={blurry}
      />
      <button onClick={nextClick}>Next</button>
    </>
  );
};

render(<Parent />, document.getElementById("root"));

How can I get it to update on enter click?

Working demo: https://codesandbox.io/s/react-typescript-7bkl7

Upvotes: 0

Views: 545

Answers (1)

Sten Muchow
Sten Muchow

Reputation: 6701

what do you want to update?

The code is working how it should in theory, but when you do a keyup call and in the event handler all you are doing is console logging the value and setting it to the new state.

THe only way to increment the number now in in the next method call.

 <input
        type="number"
        onKeyUp={handleEnterKey}
        ref={inputRef}
        defaultValue={InputVal as any}
        onBlur={blurry}
        value={InputVal as number}
      />

Upvotes: 1

Related Questions