How to fix the floating property of `TextField` in Material-UI?

Viewed 2347

I'm using material-ui textfied of type='date' when it's not animated its mixed with the date label. i want to fix that, i want it not to animate and fix on the top like in the images below

enter image description here

enter image description here

component:

<TextField 
  className={classes.inputFields} 
  error={errors.lastVisit && touched.lastVisit} 
  name='lastVisit' variant='standard' 
  type='date' 
  onChange={handleChange} 
  id='lastVisit' 
  label='Last Visit' 
  helperText={errors.lastVisit && touched.lastVisit? errors.lastVisit
    : null}
/>

and the CSS applied using makeStyles function of material-ui and the css is:

inputFields: {
  width: '100%',
  '& .MuiInputLabel-animated': {
    color: 'black',
    [theme.breakpoints.down('md')]: {
      fontSize: theme.spacing(2),
    }
  },
}

how to fix that issue?

1 Answers

The quick fix in your case is to force the label to shrink all the time. That can be done by adding InputLabelProps={{shrink: true}} to your component.

So your component should look like

<TextField
     className={classes.inputFields}
     error={errors.lastVisit && touched.lastVisit}
     name='lastVisit'
     variant='standard'
     type='date'
     onChange={handleChange}
     id='lastVisit'
     label='Last Visit'
     helperText={errors.lastVisit && touched.lastVisit? errors.lastVisit : null}
     InputLabelProps={{shrink: true}}
/>

Also if you need a datePicker and not just an input, you can check from MaterialUI the datePickers inside the MaterialUI/Pickers HERE

Related