July
July

Reputation: 558

React material-ui textfield decimal step of 1.00 on 1.00 as a default number

I'm using react material ui with this Textfield:

<TextField 
    required
    id="qty" 
    type="number"
    label="Qtà" 
    defaultValue={!props.row.qty ? '1.00' : props.row.qty} 
    step={1.00}
    variant="outlined" 
    error={HP_qty.length === 0 ? false : true}
    helperText={HP_qty}
    inputProps={{
      maxLength: 13,
    }}
    onBlur={(e) => onBlur(e,HP_qty)}/>

I would like to use the arrows in order to have a 1.00 step so on 1.00 as a default number i can visualize the 2.00 or the 0.00 number. the result for now is: 1.00 -> (arrow up) -> 2 so basically it removes zeros that I would like to have.

Upvotes: 22

Views: 48531

Answers (2)

Andrew Birks
Andrew Birks

Reputation: 890

I just wanted to add my answer, as I think there's a difference between:

inputProps & InputProps

              <TextField
                {...getFieldProps('price')}
                fullWidth
                label="Price"
                type="number"
                inputProps={{
                  step: 0.5,
                }}
                InputProps={{
                  startAdornment: <InputAdornment position="start">£</InputAdornment>,
                  endAdornment: <InputAdornment position="end">per person</InputAdornment>,
                }}
                error={Boolean(touched.price&& errors.price)}
                helperText={touched.price&& errors.price}
              />

Upvotes: 16

NearHuscarl
NearHuscarl

Reputation: 81803

Use controlled TextField and format the number every time change event fires. See this answer.

Also note that the value displayed in the TextField is now a string so you may want to convert it back to number before submitting your changes.

function App() {
  const [value, setValue] = useState("0.0");
  return (
    <TextField
      type="number"
      value={value}
      variant="outlined"
      inputProps={{
        maxLength: 13,
        step: "1"
      }}
      onChange={(e) => setValue(parseFloat(e.target.value).toFixed(1))}
    />
  );
}

Edit 66763023/react-material-ui-textfield-decimal-step-of-1-00-on-1-00-as-a-default-number

Upvotes: 26

Related Questions