0

In my return statement, I try to check for a valid number or else assign the value 0. This doesn't seem to work, is there a different way of doing this?

return (
    <Input
      color="teal"
      size="regular"
      outline={true}
      type={question?.type}
      name={question?.name}
      value={value ?? ''}
      placeholder={question?.placeholder ?? ''}
      onChange={(e: React.FormEvent<HTMLInputElement>) => {
        if (question?.type === 'number' && Number(e.currentTarget.value) < 1) {
          e.currentTarget.value = 0;
        }
        dispatch(
          setResponseGeneric({
            property: question?.name,
            value: e.currentTarget.value,
          })
        );
      }}
    ></Input>
  );

1 Answer 1

2

This is because Number('bad input') returns NaN (Not a Number). NaN is a value which is not smaller or greater than 1. You should change your condition so that it handles those scenarios.

if (question?.type === 'number' && (isNaN(e.currentTarget.value) || Number(e.currentTarget.value) < 1)) {

Also something else, besides your question, changing the element value like you do in here e.currentTarget.value = 0; is bad practice since you're changing it imperatively. It's better to make sure you're changing the state so that the value variable becomes 0 (I'm not sure if that already happens in setResponseGeneric).

Sign up to request clarification or add additional context in comments.

1 Comment

You are right actually, I'm not changing the state in setResponseGeneric not sure how to. Pretty new to react.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.