Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI Label Overlaps with Text

I'm using Material UI in a React application and trying to implement an entity update page. In this, we would need to set the exiting values of the entity to let the user update them. The existing values have been set using the defaultValue attribute of the input fields:

<div className="input-field">
   <input type="text" name="name" ref="name" defaultValue={this.state.name} />
   <label htmlFor="name" >Name</label>
</div>

With this approach, the intended functionality works fine. However, the labels of all text fields overlaps with their values. Please see below screenshot:

enter image description here

If I click on each field, the label moves up as expected. However, at the page load, labels do not move up. I tried using the value attribute of the input fields together with the onChange() event handler but experienced the same problem. Really, appreciate your thoughts on this.

The complete source code of this application can be found here: https://github.com/imesh/react-examples/tree/master/meetups/meetups-web-client

This particular page can be found here: https://github.com/imesh/react-examples/blob/master/meetups/meetups-web-client/src/components/UpdateMeetup.js

Github Issue: https://github.com/Dogfalo/materialize/issues/5995

like image 818
imesh Avatar asked Jun 20 '18 19:06

imesh


3 Answers

This is due to the undefined state of the value.

This workaround works for me as a fallback:

value= this.state.name || '';

e.g. for Material-UI

<div className="input-field">
   <input type="text" name="name" ref="name" value={this.state.name || ''} />
   <label htmlFor="name">Name</label>
</div>
like image 146
jdGhuman Avatar answered Oct 23 '22 05:10

jdGhuman


InputLabel has a prop shrink. you can use in TextField like below:

<TextField
  // ... rest
  InputLabelProps={{ shrink: true }}  
/>
like image 44
Sultan Aslam Avatar answered Oct 23 '22 06:10

Sultan Aslam


I fixed it by adding the condition on shrink based on a text field value.

Just add this code in the text field: Updated (2022)

InputLabelProps={{ shrink: field.value }}  

Example:

<Controller
name="formatted_phone_number"
control={control}
render={({ field }) => (
  <TextField
    {...field}
    className=""
    id="formatted_phone_number"
    label="Phone"
    type="text"
    variant="outlined"
    fullWidth
    InputLabelProps={{ shrink: field.value }}  
  />
)}
/>
like image 8
Taha Farooqui Avatar answered Oct 23 '22 06:10

Taha Farooqui