formsmaterial-uiformik

Formik causing MUI number textfield to lose focus


When I bind formik values to a textfield with type 'number' any attempt to manually type a number e.g. 14 in the text field allows you to enter a single number e.g. 1 before it then loses focus on the input and to add the next digit (4) you have to click on the input to refocus it once more.

When I remove value={formik.values.newValue} and onChange={formik.handleChange} you can once again type freely in the input. This would suggest that the behaviour seen has something to do with the binding between or influence of formik on the textfield.

The field is set to have a default, minimum and maximum value which is retrieved from a config file that returns the fields numerical values in the following format:

const Data: Data = {
    name: "Test Name",
    dataType: DataType.Number,
    default: 50,
    lowerBoundary: 0,
    upperBoundary: 100
  };

I've created a code sandbox demonstrating my implementation but I'd like to resolve the above issue with the field losing focus so that a user can then freely type a full number in one go.


Solution

  • The above comment answered this question and linked answer helps provide details as to why. Ultimately, I had to remove the method:

    const NumberInputComponent: React.FC<NumberInputComponentProps> = ({
        label,
        Data,
        min,
        max,
        default: defaultValue
      }) => (
        <FormControl fullWidth>
          <TextField
            id="newValue"
            name="newValue"
            label={label}
            type="number"
            value={formik.values.newValue}
            onChange={formik.handleChange}
            inputProps={{
              min: { min },
              max: { max }
            }}
            error={
              Number(formik.values.newValue) < Number(min) ||
              Number(formik.values.newValue) > Number(max)
            }
            helperText={
              Number(formik.values.newValue) < Number(min)
                ? `Below minimum: ${min}`
                : Number(formik.values.newValue) > Number(max)
                ? `Above maximum: ${max}`
                : ""
            }
          />
          <FormHelperText>
            <p>
              <b>Minimum</b> {min} <b>Maximum</b> {max}{" "}
            </p>
            <p>
              <b>Default</b> {defaultValue}{" "}
            </p>
          </FormHelperText>
        </FormControl>
      );
    

    And take the textfield and place this inside my form rather than generating it from a method to stop it from returning a new field every time a user typed and thus lose the focus on the field.