6

I am using Material-UI's TextField in conjunction with react-hook-form to watch inputs. I have noticed that regardless of the type of the input, a string is returned. This clashes with the types I use in the codebase.

I have read about different ways to handle this issue on react-hook-form's side, with transforming the returned data but I couldn't find anything about making TextField return a different type depending on how it's used. I'm especially surprised because as far as I understand, valueAsNumber exists natively on HTML inputs (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement)

1 Answers1

1

There is no way to get MUI's <TextField> to innately return a number type. This is because <TextField> is built off of the HTML <input> element, which is, by nature, a text field.

If you're able to use the <TextField> component in a controlled state, you can easily convert the returned type with the onChange handler using valueAsNumber:

<TextField
    id="outlined-controlled"
    label="Number Field"
    value={numValue}
    type="number"
    onChange={(event) => {
        setNumValue(event.target.valueAsNumber);
    }}
/>

Of course you can always get specific with the number type using methods like parseInt(event.target.value) or parseFloat(event.target.value). There are a number of conversion techniques available, laid out nicely in this article: https://www.freecodecamp.org/news/how-to-convert-a-string-to-a-number-in-javascript/.

If you're constrained to using <TextField> in an uncontrolled form-submission context, there are options available laid out in: Passing HTML input value as a JavaScript Function Parameter.