Shawn_Beans
Shawn_Beans

Reputation: 47

props.onChange(e.target.value) returns an object instead of a value in textField in material ui

  function FormInput(props) {
    const classes = formInputStyles();
    return (
      <div>
        <TextField
        onChange={(e) => props.onChange(e.target.value)}
          InputProps={{ classes, disableUnderline: true }}
          {...props}
        />
      </div>
    );
  }

when trying to pass (e.target.value) to the component it returns a object

Object { _reactName: "onChange", _targetInst: null, type: "change", nativeEvent: input, target: input.MuiInputBase-input.MuiFilledInput-input, currentTarget: input.MuiInputBase-input.MuiFilledInput-input, eventPhase: 3, bubbles: true, cancelable: false, timeStamp: 1398131, … }

<FormInput
    onChange={(value) => {
    console.log(value);
    }}
    label="Username"
    variant="filled"
></FormInput>

but when i try to alert the value it says "[object Object]"

Upvotes: 2

Views: 1860

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81803

It looks like the onChange props in the TextField is overridden by the props.onChange. This:

<TextField
  onChange={(e) => props.onChange(e.target.value)}
  InputProps={{ classes, disableUnderline: true }}
  {...props}
/>

Can be translated to:

<TextField
  onChange={(e) => props.onChange(e.target.value)}
  InputProps={{ classes, disableUnderline: true }}
  {...}
  // because you're spreading all props. props.onChange receives e (object)
  // instead of e.target.value
  onChange={props.onChange}
/>

The solution is to extract the onChange props and spread the rest like below:

function FormInput({ onChange, ...rest }) {
  const classes = formInputStyles();

  return (
    <div>
       <TextField
         onChange={(e) => onChange(e.target.value)}
         InputProps={{ classes, disableUnderline: true }}
         {...rest}
       />
    </div>
  );
}

Upvotes: 2

Related Questions