krsna
krsna

Reputation: 4333

Unable to change decimal value in MUI v5 TextField

I tried to display decimal value 1.0 in the MUI5's TextField component. I'm able to change its value only with the icons in the TextField but not when I try to input any value. Backspace does not seem to work.

Excerpt from my code

export default function App() {
  const [value, setValue] = useState(1);
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  return (
    <div className="App">
      <TextField
        fullWidth
        variant="outlined"
        id="value"
        name="value"
        type="number"
        label="Decimal Value"
        value={parseFloat(value).toFixed(1)}
        onChange={handleChange}
      />
    </div>
  );
}

I created a working example using CodeSandbox. Could anyone please help?

Upvotes: 1

Views: 879

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81350

Try formatting the value in onBlur instead of onChange. When you type backspace in onChange the value is 1. but is formatted to 1.0 anyway in the next render and undo your work:

<TextField
  type="number"
  inputProps={{
    maxLength: 13,
    step: '1',
  }}
  value={value}
  onChange={handleChange}
  onBlur={(e) => setValue(parseFloat(e.target.value).toFixed(1))}
/>

Codesandbox Demo

Upvotes: 1

Related Questions