0

I currently have an input box component and I'd like to add a script to prevent all input except for numbers.

function onChangeHandler(e: React.ChangeEvent) {
  this.value.replace(/(?![0-9])./gmi,'');
}

export function Input(props: InputProps) {
  const {
    className,
    ...restProps
  } = props;

  return (
    <input
      {...restProps}
      className={cx([inputStyles])}
      type={inputType}
      onChange={e => onChangeHandler(e)}
    />
  );
}

Currently this setup doesn't work because I get the following error from onChangeHandler: 'this' implicitly has type 'any' because it does not have a type annotation.

How can I make this work?

Note: I don't want to use type=number

1 Answer 1

1

You are trying to access this scope when there does not exist any. It's not a class, it's a function, this is not required here.

Your code should look like this (though, you could move value state to your parent component and pass it through props):

export function Input(props: InputProps) {
  const [value, setValue] = React.useState('');  

  const {
    className,
    ...restProps
  } = props;

  const onChangeHandler = (e: React.ChangeEvent) => {
    setValue(e.target.value.replace(/(?![0-9])./gmi,''));
  }

  return (
    <input
      {...restProps}
      className={cx([inputStyles])}
      type={inputType}
      value={value}
      onChange={onChangeHandler}
    />
  );
}
Sign up to request clarification or add additional context in comments.

Comments

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.