Search code examples
cssreactjsmaterial-uistyling

How do you wrap text to the next line in a material UI select/menu item component? (CSS issue)


I'm trying to show a school's cancelled classes in a select menu. It's arranged by day: Desktop view looks correct

However, my menu just cuts off the overflow text when at a mobile resolution in developer tools. enter image description here The thermodynamics class is cut off.

I'm using material ui's select menu with react. Material UI Select documentation I'm also using the menu item. I want to have classes listed overflow onto the next line. The is where I show the classes per day.

This is the code (it's just an example, and it doesn't run):

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<FormControl className={classes.formControl}>
      <InputLabel id="demo-controlled-open-select-label" > Filter classes by day</InputLabel>
     
      <Select
        labelId="demo-controlled-open-select-label"
        id="demo-controlled-open-select"
        open={open}
        onClose={handleClose}
        onOpen={handleOpen}
          defaultValue={subjectFilter}
          onChange={handleChangeSubject}
        className="styleSelect"

        >
         {item.SUBJECT === 'OPEN_LEARNING' && 
               <ul className ="stylingList">
               {(state.subjects) && state.subjects.filter(item => 
               (item.SUBJECT === 'OPEN_LEARNING')).map(item => 
                 <li className ="stList">
                   {item.CLASS_FULL}
                 </li>
                 )}
                 </ul>
              }
            </MenuItem>
            //this is just one day.  I do this for all the days.
          ) )
        }
     
        </Select>
      </FormControl>

I don't have styles on the classes listed. I just made class names to customize the areas later if needed. I just changed the text color. Thanks. I tried overflow-wrap: break-word; on the li class (stList), but it didn't make the words go to the next line.


Solution

  • TL;DR: Override the wrapping style of the Menu Item:

    const useStyles = makeStyles((theme) => ({
      root: {
        whiteSpace: "unset",
        wordBreak: "break-all"
      }
    }));
    //...
    const YourComponent =(props)=>{
        const classes = useStyles();
        //...
        <MenuItem  classes={{ root: classes.root }}>
    }
    

    NL;PR: By default, the menu item style whiteSpace: 'nowrap' prevents the other wraps to apply. You can inspect how the suggested changes work in this pastebin.

    Now, your select's menu items will go:

    From this: enter image description here to this: enter image description here.