React: Formatted number input

Date: 2021-11-30
import React from "react";
import { formatNumber } from "../shared/helpers/tsHelper";
import styles from "./CustomNumberInput.module.css";

interface IProps {
    value?: number;
    onChange: (val: number) => void
}

export function CustomNumberInput(props: IProps) {
    const { value, onChange } = props;

    const inputValue = formatNumber(value);
    const numberFromString = (s: string) => Number(String(s).replace(/[^0-9]/, "")) || 0;

    return <input
        value={inputValue}
        className={styles.numberInput}
        type="text"
        inputMode="numeric"
        onClick={(e) => e.stopPropagation()}
        onFocus={(e) => { e.target.select(); }}
        onChange={(e) => onChange(numberFromString(e.target.value))} />;
}
57560cookie-checkReact: Formatted number input