Home > Net >  Why does defaultValue not display anything inside a text field when using an API call (reactjs)
Why does defaultValue not display anything inside a text field when using an API call (reactjs)

Time:07-29

This is the code I have, but it's not displaying properly

<TextField
                size="small"
                className="typing-container"
                defaultValue={thing.thingLastName}
                label="Last Name"
                onChange={(event) => setFirst(event.target.value)}
                required
              />

when I change defaultValue to value, it displays but then you can't edit the field at all. This all displays properly when used earlier inside a h5 tag

CodePudding user response:

You probably want to store the value in local state. Something like:

const MyComp => {
  const [value, setValue] = useState(defaultValue)

  return (
    <TextField
      ...
      onChange={(event) => setValue(event.target.value)}
      value={value}
    />
  )
}

then whenever your onChange event fires, it updates the value and passes it into the TextField. We don't need to use the defaultValue prop anymore because the useState hook takes a default value and sets that as the initial value for value

CodePudding user response:

Try pass a state to value property, set the state to the default value that you want, later change the value using the onChange property.

function Comp () {
    const {value, setValue} = useState('Default Value')
return (
<TextField
 value={value}

 onChange={(event) => setValue(event.target.value)}
 required
 />

)
}
  • Related