Search code examples
javascriptreactjsuitextfieldreact-number-format

Using react-number-format: cannot type more than one symbol at once


I am using react-number-format package inside of my TextField (material-ui). It is having strange behavior and not letting me put more than one symbol at once in the TextField. When I start typing after first click the Field is not focused anymore. I have used the same thing in other projects and it is working fine but here I cannot see from where the problem is coming. Here is the sandbox:

https://codesandbox.io/s/little-cherry-ubcjv?file=/src/App.js

import React,{useState} from 'react'
import { TextField} from "@material-ui/core";
import NumberFormat from "react-number-format";

export default function App() {
  const [minAssets, setMinAssets] = useState();

const NumberFormatCustom = (props) => {
    const { inputRef, onChange, ...other } = props;
    return (
      <NumberFormat
        {...other}
        getInputRef={inputRef}
        onValueChange={(values) => {
          onChange({
            target: {
              name: props.name,
              value: values.value,
            },
          });
        }}
        thousandSeparator
        isNumericString
        prefix="$"
      />
    );
  };
  return (
    <div className="App">
        <TextField
          label="Min Assets"
          value={minAssets}
          onChange={(e) => setMinAssets(e.target.value)}
          name="minAssets"
          variant="outlined"
          id="Minimum-Income-filter"
          InputProps={{
            inputComponent: NumberFormatCustom,
          }}
        />
    </div>
  );
}

Solution

  • In your case you don't really need the onValueChange prop on the NumberFormat component since you already have an onChange on the TextField component that update the minAssets state.

    So you can directly use this minAssets as the value of the prop value from NumberFormat like:

    return (
      <NumberFormat
        {...other}
        value={minAssets}
        getInputRef={inputRef}
        thousandSeparator
        isNumericString
        prefix="$"
      />
    );
    

    Edit trusting-waterfall-3wvby