Рома Бойко
Рома Бойко

Reputation: 87

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} />;
      }
    }

Upvotes: 4

Views: 17326

Answers (2)

Łukasz Jagodziński
Łukasz Jagodziński

Reputation: 3089

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.

Upvotes: 2

reisdev
reisdev

Reputation: 3403

You should pass a value to the this.props.onChange(), not the event, and you shouldn't set it to null. Set it to a empty string. So, you should do:

onInputChange(event) {
    var fieldValue = event.target.value; // It should be a var, then you can update it
    if (!fieldValue) {
        fieldValue = "";
    }
    this.props.onChange(fieldValue);
}

Upvotes: 1

Related Questions