2
votes

Good afternoon devs !!

I have a little problem, I'm using reactJS, and I'm using react-form-hook, in which I use an TextField from Material-UI. When I fill an input with name cep, it calls a function that sends the content from this to an api, which returns, content to fill the input there, The problem happens that when I try to set my inputs with the returned content. The Input label remains on the field, as in the case shown in the photo, in the last input. That came the answer.

the fields first with the setValues ​​of the react-form-hook, but the error persisted after I tried to set this way document.querySelector ('# inputStreet'). value = street;

Finally the way I decided was to create in this inputs that receive update a useState for each

const [srua, setSrua] = useState ('');
const [sbairros, setSbairros] = useState ('');
const [scity, setScidade] = useState ('');
const [sUF, setSUF] = useState ('');

Only in this way was he able to solve the problem of the label not being on the content of the input, as already exemplified in the photo in the last input, I believe this is not the most correct way, so I would like a help on how to solve this in a more efficient. just like that

Repository link.

enter image description here

1

1 Answers

2
votes

The problem with your TextField is that the InputLabel does not shrink. the label shrinks when the TextField is in focus or when the value of the TextField is not empty.

But since you are setting the value programmatically, the input is not focused, the value is also not registered because it's uncontrolled which means the TextField keeps track and updates the value internally for you and ignore external value if provided.

In order to make the TextField controllable, as suggested from the name, you must take control of the TextField's value from the beginning which is what you did in the question.

You can also simplify this process by using react-hook-form's Controller. It's a wrapper component to help you pass common props to the controlled components

<Controller
  render={({ onChange, onBlur, value, name }) => (
    <TextField
      onBlur={onBlur}
      onChange={(e) => onChange(e.target.value)}
      value={value}
      name={name}
      label="Email"
    />
  )}
  name="email"
  control={control}
  // need to initialize value to register the TextField as controlled
  // if we don't provide, the default value is undefined, which means uncontrolled
  defaultValue=""
/>

Which can be shortened to this

<Controller
  render={(props) => <TextField {...props} label="Email" />}
  name="email"
  control={control}
  defaultValue=""
/>

Live Demo

Edit 63973773/error-when-setting-an-input-in-reactjs-label-is-over-overwrites-the-value-of