Material UI TextField label does not move up when the value for TextField is set porgramatically

Viewed 1821

I have a TextField element that is connected to react-hook-form. When I focus on that input I open a list of countries, so that I can choose a country to populate its phone code into the field through setValue function from react-hook-form.

Everything works okay, the country code does appear in the field but the label that normally moves up when you enter a text manually does not move up.

Here is what it looks like enter image description here

2 Answers

Add this

InputLabelProps={{ shrink: true }}

to your TextField properties.

I also had same issue when i was updating textfield value programmatically in my reactjs project, what worked for me is using javascript ternary operator as shown in code below:

const [name,setName]=useState('')

somefunction = () => setName('abc')

        <TextField
          required
          variant="outlined"
          label="...some label..."
          // value={name} instead of this line write below line
          **value={name ? name : ''}**
          onchange={...somefunction...}
        />
Related