Home > database >  Why does the value of the input box turn to string after I type in a number?
Why does the value of the input box turn to string after I type in a number?

Time:02-28

Hi I have a small React app that can increase by 1 when user click on a button. User can also type in the value they want in the input box. However, when I type in a value and then click the button, the value is treated a string not a number i.e. 4 -> 41 -> 411 instead of 5 and 6. This works fine if I click the button without type in the value i.e. 0->1. Does anyone know why this happens ? Thanks

export default function App() {
  const [value, setValue] = React.useState(0);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <input
          value={value}
          onChange={(event) => {
            setValue(event.target.value); // -> still a number
            console.log(typeof value);
          }}
        />

        <button
          onClick={() => {
            console.log(typeof value); // -> it is a string
            setValue(value   1);            
          }}
        >
          Click me
        </button>
      </div>
    </div>
  );
}

CodePudding user response:

It's because the values inputs generate are strings. If you attempt to do "addition" with a string and a number, javascript will "assume" you want a string back and to treat both the number and the string as strings.

If you want to make sure your state stays a number type, just wrap your value like so setValue(Number(event.target.value)). Your button should be fine because it is the input that converts your state to string so if that is taken care of you don't need to do anything else.

CodePudding user response:

Value of e.target.value will always be string and it does not depend on type of input. To achieve what you want you need to cast the string you are receiving from input to an integer. By using parseInt function provided by javascript

  export default function App() {
  const [value, setValue] = 
  React.useState(0);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <input
          value={value}
          onChange={(event) => {
            setValue(event.target.value); // -> still a number
            console.log(typeof value);
          }}
        />

        <button
          onClick={() => {
            console.log(typeof value); // -> it is a string
            setValue(parseInt(value)   1);  //-> line changed added parseInt         
          }}
        >
          Click me
        </button>
      </div>
    </div>
  );
}
  • Related