Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set input value to null in react

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} />;
      }
    }
like image 882
Рома Бойко Avatar asked Sep 03 '25 08:09

Рома Бойко


1 Answers

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.

like image 65
Łukasz Jagodziński Avatar answered Sep 04 '25 22:09

Łukasz Jagodziński