Home > Enterprise >  What is a NaN, and how do I fix it?
What is a NaN, and how do I fix it?

Time:08-09

I'm trying to sum the values in the input and print them to the screen, but it returns a NaN error. Even though I type parseInt, I get a NaN error when I click on the button. Where am I making a mistake?

function Button() {

  const [input, setInput] = useState({
    i1: "",
    i2: "",
  });

  const [result, setResult] = useState("");
  const onChangeInput = (event) => {
    const value = event.target.name;
    setInput({
      ...input,
      [event.target.name]: value,
    });
  };

  const sum = () => {
    const { i1, i2 } = input;
    const newSum = parseInt(i1)   parseInt(i2); //NaN
    setResult(newSum);
  };

  return (
    <div>
      <input type="text" name="i1" onChange={onChangeInput} /> <br />
      <input type="text" name="i2" onChange={onChangeInput} /> <br />
      <button onClick={sum}>Click</button>
      <div className="result">Result: {result} </div>
    </div>
  );
}

export default Button;

CodePudding user response:

You are setting value as event.target.name instead event.target.value:

  const onChangeInput = (event) => {
    const value = event.target.name; // replace with [event.target.value]
    setInput({
      ...input,
      [event.target.name]: value,
    });
  };

This causes the value be a simple string and not a numeric string as you were expecting when making the sum. So the parseInt returns a value indicating you're trying to convert something is not a number (NaN).

CodePudding user response:

const value = event.target.name;

You're setting your value to be the name of your input. Instead you should write:
const value = event.target.value;

CodePudding user response:

You've some error in the onChangeInput function.

Change this line

const value = event.target.name;

to this line

const value = event.target.value;
// or destructure the object
const {value} = event.target;
  • Related