Why I can't set target value to null if target value is empty str ?
here is my code, hope you'll help me:
class Input extends React.Component {
constructor(props) {
super(props);
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
const fieldValue = event.target.value;
if (!fieldValue) {
event.target.value = null;
}
this.props.onChange(event);
}
render() {
return <input value={this.props.value} onChange={this.onInputChange} />;
}
}
It's an old issue but maybe this answer will help someone. If you're working with Material UI and Formik then this might be helpful:
import TextField from "@material-ui/core/TextField";
import * as React from "react";
export interface TextFieldProps {
className?: string;
disabled?: boolean;
fullWidth?: boolean;
helperText?: string | JSX.Element;
multiline?: boolean;
name: string;
label: string;
onChange?(event: React.ChangeEvent<{ value: string | null }>): void;
required?: boolean;
rows?: number;
type?:
| "text"
| "color"
| "date"
| "email"
| "password"
| "number"
| "tel"
| "time"
| "url"
| "hidden";
value?: string | null;
}
export const NullableTextField: React.FC<TextFieldProps> = (props) => {
const { onChange, value, ...restProps } = props;
const handleChange = React.useCallback<
(event: React.ChangeEvent<{ name?: string; value: string | null }>) => void
>((event) => {
const value = event.target.value;
if (value === "") {
event.target = {
...event.target,
name: event.target.name,
value: null,
};
}
onChange?.(event as React.ChangeEvent<{ value: string | null }>);
}, []);
return (
<TextField
{...restProps}
onChange={handleChange}
value={typeof value === "string" ? value : ""}
variant="outlined"
/>
);
};
Btw. it's pretty annoying that you have to do some extra work to make sure that empty values are nulls
and it's not default behavior.
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