A guide on wrapping text within a Material-UI MenuItem

I am struggling to display text in a popover in multiple lines for UI reasons. I have tried updating the code but so far, I have not been successful. Any suggestions?

<Popover
  anchorEl={target}
  open={open}
  anchorOrigin={{ horizontal: 'middle', vertical: 'bottom' }}
  targetOrigin={{ horizontal: 'left', vertical: 'bottom' }}
  onRequestClose={handleRequestClose}
  animation={PopoverAnimationVertical}
>
  <Menu autoWidth={true}>
    <MenuItem style={{ width: '200px', height: '200px' }}>
      <p style={{ display: 'flex', flexWrap: 'wrap' }}>
        'aslkjflajdsljflskdjflsdfjlsjdfjdfjlasjkfadlsf'
      </p>
    </MenuItem>
    //this does not work....
  </Menu>
</Popover>

Answer №1

Consider trying a different approach by adjusting the whiteSpace style property.

 <MenuItem style={{whiteSpace: 'normal'}}>  
   <p>This particular tune consists of only six words. This particular tune consists of only six words.  This particular tune consists of only six words.  This particular tune consists of only six words.</p> 
 </MenuItem>

Answer №2

To ensure that long text wraps properly in the MenuList component, you can set the whiteSpace property to normal using the sx prop as shown below:

<Menu
  {...}
  MenuListProps={{
    sx: {
      width: 230,
      '& .MuiMenuItem-root': {
        whiteSpace: 'normal',
      },
    },
  }}
>

If you want all MenuItem elements in your application to automatically wrap long text, you can accomplish this by defining it within the createTheme method:

const theme = createTheme({
  components: {
    MuiMenuItem: {
      styleOverrides: {
        root: {
          whiteSpace: 'normal',
        },
      },
    },
  },
});

https://codesandbox.io/s/39400950-how-to-text-wrap-the-menu-item-in-material-ui-t9z2j?file=/demo.tsx

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

Is it possible to modify a website's CSS permanently using just the browser?

Is there a way to make changes to CSS in a large project using Firefox's built-in developer tools and have them saved permanently? I've been trying to edit the style sheets, but couldn't locate the specific property I needed. Since I can&apo ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

Encountering an issue... invariant.js:42 Error: A `string` value was received instead of a function for the `onClick` listener

Currently, I am working on creating a form that allows users to build quizzes without any restrictions on the number of questions they must include. To achieve this, I plan to add an "add question" button at the bottom of the quiz form, allowing users to d ...

Achieving a transparent background color for a div without affecting the content with CSS

I am attempting to design a div element with a basic background color and some text displayed on it. I would like to lower the opacity of the background color in this div, but every time I try, the opacity of the text also changes. Is there a way to adjust ...

Styling applied exclusively to the field for mobile devices

As I work on creating a navigation bar using Bulma and Vue.js, I encounter an issue with the dropdown menu behavior. When the navbar collapses into the hamburger menu, the dropdown list remains in display: block; mode. To address this, I attempted a workar ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

Troubleshooting: React.forwardRef and Typescript defaultProps not functioning correctly

I am currently working on migrating components from a js to ts react component library for my own project. The library was originally written in js using a customized material-ui library. My task now is to migrate these components one by one. Here is an ...

configure redirects for specific file extensions based on regular expressions

Attempting to create a redirect rule in next.config.js to send all requests with .pdf extension to an external URL is resulting in the following error. Error encountered while parsing `/:file(.(pdf)$)` https://err.sh/vercel/next.js/invalid-route-source Rea ...

Creating a Higher Order Component for authentication in Next.js: A Step-by-Step Guide

I am in the process of developing a basic Next.js HOC for authentication. Despite my efforts to find a solution, I haven't been successful so far. Within my Next.js app, there is an admin page that needs to fetch data from http://localhost:4000/user/ ...

React functional component fails to update upon form submission

I am currently working on developing a functional component using Redux hooks that allows the user to edit a note. Everything appears to be functioning correctly, but when I submit the form with changes, it reloads itself without any updates being made. It ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here My code successfully shows and hides the navigation items, but it's not updating the burger icon No console errors or warnings are present This is my HTML: <nav> ...

The specified property cannot be found in the type 'IntrinsicAttributes & ...'

I'm currently working on adding a custom prop to a custom styled-component: interface Props { image?: string; title?: string; subtitle?: string; background?: string; } export function CardWide({ image, title, subtitle, background }: Props) ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

Larger Material UI icons contribute to significant Cumulative Layout Shift

I am facing an issue with my website that is built using React, Nextjs, and Material UI Every time the page loads, there is a significant Cumulative Layout Shift caused by an SVG Material UI Icon that initially renders large before adjusting to the styled ...

What causes delayed state updates in React/NextJS until another state is updated or a fast refresh occurs?

UPDATE: Version 13.3.0 is coming soon! In my code, I have a state variable named localArray that I need to update at a specific index. To achieve this, I decided to create a temporary array to make modifications and then set the state with the updated val ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

How can I retrieve information on a logged in Auth0 user from an API?

I'm currently working on a React application that utilizes auth0 in conjunction with an express API server. One issue I'm facing is how to access user information within the API when a secure endpoint is called. While I can retrieve user data on ...

Methods for dynamically altering the background color of a parent component from a child component

Currently, I am working on a T-shirt design application using fabric.js within reactjs. I have encountered an issue when attempting to change the color of the t-shirt. My goal is to allow the color of the T-shirt to be changed from the child component but ...

Tips for avoiding accidentally selecting nearby text while holding down a button on your mobile device

My application requires the user to press and hold a button to record audio. However, on mobile devices, when the user holds the button, the browser attempts to select nearby text due to finger pressure. While this behavior is understandable, I want to pre ...