Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 222
Oleksandr Fomin Avatar asked Sep 05 '25 03:09

Oleksandr Fomin


2 Answers

I also had this issue when I was updating a TextField value programmatically in my ReactJS project. What worked for me is using the 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...}
/>
like image 59
Ahir Hiten Avatar answered Sep 07 '25 20:09

Ahir Hiten


Add this

InputLabelProps={{ shrink: true }}

to your TextField properties.

like image 43
Muhammad Anies Avatar answered Sep 07 '25 19:09

Muhammad Anies