javascriptreactjsmaterial-uimui-x

React material-ui InputLabel component not working accordingly


I want the label to be displayed properly and take width according to its value, i.e., criteria (Roles, No. of Employees, etc.) and don't want to give it a fixed width.

But the label is not fully displayed, i.e., not taking width properly. I don't want to give the FormControl fullWidth prop. Below is the code. (I will change the values for MenuItems later, I want to to fix this issue first.)

function Filter() {
        const filterCritieria=[
            'Roles','No of Employees','Experience','Remote','Minimum Base Pay Salary'
        ]
      return (
       <>
       {filterCritieria.map((criteria,index)=>(
           <FormControl key={index} sx={{  margin: '10px' }} >
               <InputLabel  htmlFor={criteria} >{criteria}</InputLabel>
               <Select
                   value={12}
                   label={criteria}
                   id={criteria} 
                   
               >
                   <MenuItem value={10}>Ten</MenuItem>
                   <MenuItem value={20}>Twenty</MenuItem>
                   <MenuItem value={30}>Thirty</MenuItem>
               </Select>
           </FormControl>
       ))}
       </>
      )
    }

Solution

  • If you don't want to give the FormControl fullWidth prop, you can add a dynamically width in px to the FormControl, by getting the length of the criteria multiplyed by 20, to make sure that you will have an additonal space after the criteria. See an example bellow:

    import { FormControl, InputLabel, MenuItem, Select } from '@mui/material'
    import React from 'react'
    
    function Filter() {
        const filterCritieria=[
            'Roles','No of Employees','Experience','Remote','Minimum Base Pay Salary', 'Minimum Base Pay Salary Minimum Base Pay Salary'
        ]
      return (
       <>
       {filterCritieria.map((criteria,index)=>(
           <FormControl key={index} sx={{  margin: '10px', width: `${criteria.length * 20}px` }} >
               <InputLabel  htmlFor={criteria} >{criteria}</InputLabel>
               <Select
                   value={12}
                   label={criteria}
                   id={criteria}               
               >
                   <MenuItem value={10}>Ten</MenuItem>
                   <MenuItem value={20}>Twenty</MenuItem>
                   <MenuItem value={30}>Thirty</MenuItem>
               </Select>
           </FormControl>
       ))}
             
             
            
       </>
      )
    }
    
    export default Filter;
    

    Hope this helps you, good luck!