3

I'm trying to create a sort of expense manager and I'm having an issue where the numbers I submit gets added as a string and not as an int. i made sure that the default is set as an integer and not as a string.

The "problematic" component is the Income component (which i have highlighted)

App:

import Outcome from "./components/Outcome";
import Income from "./components/Income";

const App = () => {
  const [sum, setSum] = useState(0);

  const onChangeHandlerOutcome = (value) => {
    setSum(sum - value);
  };

  const onChangeHandlerIncome = (value) => {
    setSum(sum + value);
  };

  return (
    <div>
      <Outcome onChangeHandlerOutcome={onChangeHandlerOutcome} />
      <Income onChangeHandlerIncome={onChangeHandlerIncome} />
      You have {sum}$!
    </div>
  );
};

export default App;

Income component


const Income = (props) => {
  const [input, setInput] = useState(0);

  const setInputHandler = (e) => {
    e.preventDefault();
    setInput(e.target.value);
    props.onChangeHandlerIncome(input);
  };

  return (
    <div>
      <form onSubmit={setInputHandler}>
        <label>
          Income
          <input
            type="text"
            name="name"
            onChange={(e) => setInput(e.target.value)}
          ></input>
        </label>
        <input type="submit" value="Submit"></input>
      </form>
    </div>
  );
};

export default Income;

Outcome component :


const Outcome = (props) => {
  const [input, setInput] = useState(0);

  const setInputHandler = (e) => {
    e.preventDefault();
    setInput(e.target.value);
    props.onChangeHandlerOutcome(input);
  };

  return (
    <div>
      <form onSubmit={setInputHandler}>
        <label>
          Outcome
          <input
            type="text"
            name="name"
            onChange={(e) => setInput(e.target.value)}
          ></input>
        </label>
        <input type="submit" value="Submit"></input>
      </form>
    </div>
  );
};

export default Outcome;
NewbieAeg
  • 557
  • 3
  • 8
  • 15

1 Answers1

5

In onChange={(e) => setInput(e.target.value)} the value of e.target.value will always be a string. You can use parseInt(e.target.value) to convert to an integer. Or use parseFloat for floats.

This will not handle international number (using a different decimal separator then ".") well, so be aware you might need more magic in your conversion from string to number than parseInt.

pintxo
  • 2,085
  • 14
  • 27