melv3223
melv3223

Reputation: 105

MUI Select Border not extending to label, white space

I am trying to render a dropdown using @mui/material/Select and want the top border to extend next to the label. Right now there is white space between the label and the right edge of the dropdown div. I checked dev tools and the only border property I could identify was border-radius. Is there a way to make the border extend up next to edge of the label ?

Rendered Dropdown

YearDropdown.js

import React from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import styled from 'styled-components';

import { BEM_Date } from 'containerMfe/Functions';

const Form = styled(FormControl)`
  width: 80px;
  margin-bottom: 15px!important;

  & > div > div {
    padding: 10px;
  }
`

export default function YearDropdown({ columns, yr, handler }) {
  const years = [...new Set(columns.map(date => BEM_Date(date).getFullYear()))]
  
  return (
    <React.Fragment>
      <Form>
        <InputLabel id='year-dropdown-label'>Year</InputLabel>
        <Select
          fullWidth
          labelId='year-dropdown-label'
          id='year-dropdown'
          value={yr}
          onChange={handler}
        >
          {years.map(year => <MenuItem key={'year-' + year} value={year}>{year}</MenuItem>)}
        </Select>

      </Form>
    </React.Fragment>
  )
}

Upvotes: 1

Views: 1132

Answers (1)

huntzinger92
huntzinger92

Reputation: 162

I ran into the same issue and could not solve it with the Select component, but I did find a workaround. In my case, not setting a value or default value seemed to fix the label issue, but my input had to be controlled.

What did work was using the TextField component, with the select prop set to true with InputLabelProps={{ shrink: true }}.

Here is my original Select component, whose label I could not fix, followed by an equivalent TextField example that works:

// original select implementation with broken label
<FormControl fullWidth>
  <InputLabel id="sort-by-label">Sort By</InputLabel>
  <Select
    label="sort-by-label"
    labelId="sort-by-label"
    id="sort-by"
    value={sortBy}
    onChange={handleSortByChange}
    variant="outlined"
  >
    {keys.map((key) => (
      <MenuItem key={key} value={key}>
        {key}
      </MenuItem>
    ))}
  </Select>
</FormControl>

// equivalent TextField implementation that seems to have a functional label
<TextField
  select
  value={sortBy}
  onChange={handleSortByChange}
  variant="outlined"
  label="Sort By"
  InputLabelProps={{ shrink: true }}
>
  {keys.map((key) => (
    <MenuItem key={key} value={key}>
      {key}
    </MenuItem>
  ))}
</TextField>

Upvotes: 2

Related Questions