Is there a way to align the Material UI mobile menu to the left edge of the screen?

Need help with this UI issue:

Currently working on designing a mobile web app using React and Material UI. I'm struggling to get the sidebar menu to start from the left edge of the screen, as it seems to have an unwanted margin preventing it. Any suggestions on how to fix this?

Here's a snippet of my code:

<Menu
    className='menu-style'
    anchorReference="anchorPosition"
    anchorPosition = {{top: 90, left: 0}}
    anchorOrigin={{vertical: 'top', horizontal: 'left'}}
    transformOrigin={{vertical: 'top', horizontal: 'left'}}
    anchorEl={null}
    open={isOpen}
    onClose={() => setIsOpen(false)}
    PaperProps={{
        style: {
            width: '80vw', 
            margin: '0 !important',
            height: '100vh',
        },
    }}
>
    <MenuItem onClick={() => setIsOpen(false)}>
        <a href='#'>Buy</a>
    </MenuItem>
</Menu>

Tried setting margins to 0 in the paper props style but no luck. The dropdown menu still starts slightly after the left edge. No margins are set in any parent components either.

Answer №1

Do you think using a Drawer component would be more suitable for your current scenario?

In addition, you have the option to utilize the sx prop or leverage the styled functionality along with the provided class definition menuClasses in order to statically position the menu.

import * as React from 'react';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import { menuClasses } from '@mui/material';

export default function PositionedMenu() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div style={{ textAlign: 'right' }}>
      <Button
        id="demo-positioned-button"
        aria-controls={open ? 'demo-positioned-menu' : undefined}
        aria-haspopup="true"
        aria-expanded={open ? 'true' : undefined}
        onClick={handleClick}
      >
        Dashboard
      </Button>
      <Menu
        id="demo-positioned-menu"
        aria-labelledby="demo-positioned-button"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        sx={{
          [`& .${menuClasses.paper}`]: {
            left: '0 !important',
          },
        }}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>
  );
}

The use of !important is necessary in this case due to the conflict with popper, which automatically positions the menu by directly applying styles for left and top.

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

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

Trouble altering an attribute using jquery

Hey there, I'm struggling with changing the attribute for an id and can't quite pinpoint where I'm going wrong. It's not making things easier that I'm pretty new to this whole thing as well. I've created a function to ensure ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...

What is the secret to creating a button that can sort text and another button that flips the word density in my content?

I'm not a fan of having something like this because it's displeasing to the eye: https://i.stack.imgur.com/3F4sp.jpg Instead, I prefer my word density to be more organized and structured. How can I achieve this? Sort by highest word density fi ...

Sending data between pages in Next JS/React by passing props

Looking for help with passing props to a new page in Next JS. I have an array being mapped through, and each item should link to a page where data from the array can be used as props: {mentors.map((mentor) => ( <Link href="/develop ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

Having trouble getting Laravel Full Calendar to function properly with a JQuery and Bootstrap theme

Using the Laravel full calendar package maddhatter/laravel-fullcalendar, I am facing an issue where the package is not recognizing my theme's jQuery, Bootstrap, and Moment. I have included all these in the master blade and extended it in this blade. ...

I am encountering a CORS error when trying to fetch data from the MongoDB Atlas Data API. What might be the reason for

please provide proper image description I am encountering a CORS error when trying to fetch data from the MongoDB Atlas API. Interestingly, the request works without any issue in Postman and Thunderclient. ...

Why is it that even though I update the state using useState, when I try to access the state afterwards,

I have been working on a function that updates my states dynamically. Here is the code snippet: const refreshAfterCreate = async () => { try { const res = await fetch(process.env.NEXT_PUBLIC_MICROSERVICE_COMPANY_URL + '/companies&apo ...

Attention: React is unable to identify the `pId` property on a DOM element

After removing the span tag below, I noticed that there were no warnings displayed. <span onClick={onCommentClick} className={'comment'}> <AiOutlineComment className={"i"} size={"20px"}/> Co ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Keeping calculated values in the React state can cause issues

In an attempt to develop a component resembling a transferlist, I have simplified the process substantially for this particular issue. Consider the following example: the react-admin component receives two inputs - a subset of selected items record[source ...

Is it possible to execute my react project on my smartphone while connected to the same network?

Is there a way for me to access my localhost:3000 react app on my smartphone? I'm using vite to launch the app. I attempted to connect both devices to the same network and access it from my phone. ...

What is the process of setting up various initialization parameters for a DataTable?

Here is a snippet of JavaScript code I have been using to initialize a DataTable: $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', &a ...

Exploring the depths of jQuery promises

My journey into the world of promises has just begun, and I must say it's been quite intriguing. However, there are some questions that have been lingering in my mind. It seems to me that $.Deferred().promise, $.get().promise, and $.fn.promise().pro ...

"When testing with an API client, NextJS 13 successfully returns a response, however, the same response

Having trouble getting a clear answer on something really simple. I've created an API route: // /api/test/route.js export async function GET(request, response) { console.log("requested"); return NextResponse.json({ my: "data" ...

Experiencing problems with React createContext in Typescript?

I've encountered a strange issue with React Context and Typescript that I can't seem to figure out. Check out the working example here In the provided example, everything seems to be working as intended with managing state using the useContext ...