I have a Material-Ui TextField handled with Formik. Input value (string) is converted to number on Input Change.
My problem is that when the value number zero passes, it's considered as a false value and renders an empty string. I want it to get 'number zero' showing in TextField.
If I removes TextField value condition ( value || ' ' ), It will give me a warning message below.
Warning: `value` prop on `input` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.
How can I work around with it ?
const Input = ({
classes,
icon,
styleName,
field: { name, value, onBlur },
form: { errors, touched, setFieldValue },
...props
}) => {
const errorMessage = getIn(errors, name);
const isTouched = getIn(touched, name);
const change = (e, name, shouldValidate) => {
e.persist();
const inputValue = e.target.value;
let value;
if (inputValue !== '') {
value = isNaN(inputValue) ? inputValue : parseInt(inputValue, 10);
} else {
value = null;
}
return setFieldValue(name, value, shouldValidate);
};
return (
<TextField
name={name}
value={value || ''}
onChange={e => change(e, name, true)}
onBlur={onBlur}
{...props}
className={classes[styleName]}
helperText={isTouched && errorMessage}
error={isTouched && Boolean(errorMessage)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Icon
name={icon}
width="30"
height="30"
viewBox="0 0 30 30"
fill="none"
/>
</InputAdornment>
),
}}
/>
);
};
I experienced a situation like this in some of our projects.
This isn't specific to Material-UI but to react.
To work around this, just set the initial value to an empty string ''.
So far we're fine with setting the value to an empty string since it's the default event.target.value of input type number when it's empty.
See: https://codesandbox.io/s/affectionate-stonebraker-cgct3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With