In a material UI select/menu item component, how can text be wrapped to the next line? (CSS challenge)

I am currently working on displaying a school's canceled classes in a select menu, organized by the day: https://i.sstatic.net/uCikq.png

However, I have run into an issue where the overflow text is being cut off in my menu when viewed at a mobile resolution in developer tools. https://i.sstatic.net/Ap4ie.png Specifically, the thermodynamics class is getting cut off.

For this task, I am using Material UI's select menu with React. You can find more information about Material UI Select here. Additionally, I am utilizing the Menu Item component which can be explored further here. My goal is to allow the classes to list overflow onto the next line within the menu, as shown per day.

The code snippet provided below (which is just an example and not executable) demonstrates how I have set up the functionality:

<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>

Currently, I have not applied any styles to the listed classes. However, I have assigned class names to allow for customization in the future if needed. At the moment, I have only changed the text color. I attempted using overflow-wrap: break-word; on the li class (stList) but it did not result in the words moving to the next line as intended.

Answer №1

Summary: Change 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 }}>
}

Noteworthy Point: The default menu item style whiteSpace: 'nowrap' prevents other wraps from being applied. You can see how the recommended changes function in this snippet.

After making these adjustments, your select's menu items will transition:

From this: https://i.sstatic.net/ZJKvz.png to this: https://i.sstatic.net/E2g3n.png.

Answer №2

Replace MenuItem with ListItem:

<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>
          }
        </ListItem>
        //this is just one day.  I do this for all the days.
      ) )
    }

  </Select>
</FormControl>

Answer №3

For my scenario, I opted to utilize the Typography component with the noWrap prop so that the text could be wrapped inside the MenuItem.

The implementation is as follows:

const generateStyles = makeStyles({
  menuItem: {
    display: 'block',
  },
});

const CustomizedMenuItem ({ value, primaryText, secondaryText }) => {
 const classes = generateStyles();

 return ( 
  <MenuItem value={value} className={classes.menuItem}>
   <Typography variant="body2" noWrap>
     {primaryText}
   </Typography>
   <Typography variant="caption" noWrap>
     {secondaryText}
   </Typography>
  </MenuItem>
 )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble parsing a JSON object using the fetch method in React while trying to retrieve data from my database

While using fetch with the "get" method, I encountered an issue where passing the response from my SQL database to my object using useState results in an empty object. However, when I print the response data from my database through console logs, it shows ...

Creating a responsive layout in Bootstrap 4 with three columns in a row, each with varying widths that maintain their positioning and don't stack when the

I've been searching for an answer to this question but couldn't find it. I want to arrange three columns in a row, with the middle column taking up 50% of the space and the left and right columns each taking up 25%. I don't want them to stac ...

Safari miscalculating % widths for floated inline-block elements

I am currently utilizing the JQDateRangeSlider for its intended purpose. However, I have encountered an issue with the Ruler component, specifically in displaying new months/years, similar to the example showcased here: During testing on Safari, I noticed ...

Unable to locate an image when using .find() in ReactJs

When trying to display the selected item image, only alt attributes are being displayed. In my App.js file: <Route path="/Item/:id" element={<Item />} /> This is how I styled my Link in Trending.js using MUI: <StyledLink to={& ...

How can I prevent excessive re-rendering of a React Timer?

When the seconds count is 2, it displays 1,2. And when the seconds count is 3, it displays 1,2,3. Why does this keep rendering multiple times and why doesn't the timeout function work properly? Am I overlooking something? const Timer = () => { co ...

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Elements within the div are overlapping each other

Despite adding margin, my h3 tag and p tag in a div keep overlapping. .title { margin: 0 0 26px; width: 335px; height: 28px; font-size: 24px; font-stretch: normal; font-style: normal; line-height: 36px; letter-spacing: 0; text-align: c ...

CSS property that determines where a string can be broken into lines based on specific characters

Is it possible to specify characters on which a long string, such as a URL, should break in browsers? For instance: https://www.this-is-my-url.org/upload_dir/2015/01/foo_bar_faq.pdf If the box only allows 40 characters per line, it might break like this ...

"Utilizing Material UI's autocomplete feature for handling both value updates and

I am currently working on implementing auto complete functionality on a Material UI component. Below is the code provided by Material UI: <Autocomplete id="combo-box-demo" options={top100Films} getOptionLabel={option => option.t ...

Is it possible to dynamically organize MUI cards in a React application to maximize the use of available space?

Here is the current look: old I am aiming for this desired look: new This setup uses MUI grid: <Grid container spacing={2}> <Grid item xs={12} md={6}> <Box className="white-card"> ....content... ...

Unable to view newly added components

I am currently in the process of setting up a website, focusing on arranging and formatting everything on the page before moving on to styling and adding JavaScript. I recently added three div tags after my form to create three separate columns in the ne ...

Relaying numerous references in TypeScript

Having some trouble forwarding an object of refs in TypeScript and struggling with how to properly type them. Here are the refs and the way I'm passing them into my component. const storyRef = useRef<HTMLElement>(null); const parcoursRef = useR ...

Display only one dropdown menu at a time

Hey there, I'm currently working on a dropdown menu and struggling to figure out how to keep only one item open at a time. I've tried using an array with useState for all my dropdowns but haven't been able to find a solution yet: code co ...

React.js - Time Flies

I'm having trouble extracting the date from MongoDB and displaying it in a textbox. The format of the date in MongoDB is: mmm dd yyyy hh mm ss a <input name="date" type="date" disabled={ this.state.mode } value={ this.state.it ...

Building a HTML table using PHP

My goal is to generate a dynamic table using data from mysql. I am trying to create the table layout as shown in 'demo1', but I am facing challenges with the formatting, similar to what is depicted in 'demo'. The query and values are co ...

What is the problem with locating elements in Selenium with Java?

I've been encountering difficulties in finding elements on a webpage structured like this: <tr id="filter100" style="...." idx=0 <td> <div onclick=... style=... <table dir = "fil"> <tbody> ...

Altering button appearance when mouse hovers in ASP.NET

Is there a way to modify the shape and style of a button in ASP.NET when hovering with the mouse? Specifically, I am looking to create a circular button effect during hover using ASP.NET. ...

Updating a component using React when a button is clicked

I'm working with two React components and I'm trying to achieve a scenario where clicking a button in one component will completely replace it with the second component. Below is my App Component: const App = () =>{ const[showMarketing, ...

Trouble encountered when trying to send a post request in React and Express with Nodemailer

Having some trouble using nodemailer in an express/reactjs stack. In the reactjs component, the handleSubmit function is as follows: handleSubmit = async e => { console.log(e); e.preventDefault(); await axios .post("http://localhost: ...

Is there a way to eliminate the padding for the bootstrap jumbotron specifically on mobile devices?

Hello, I am currently utilizing the bootstrap jumbotron class and facing an issue - when the screen size drops below 500 pixels, I want to remove the padding that is automatically set by Bootstrap (padding: 2rem 1rem;). However, I'm struggling to over ...