Changing the initial placement of GridActionsCellItem in Material-UI's DataGrid

I'm currently working on customizing the placement of the GridActionsCellItem elements within the MUI DataGrid component. My goal is to alter the default position of the actions menu in relation to its trigger element. The actions menu relies on a Popper component (base-Popper-root) for positioning, but I haven't been able to directly adjust this through props.

Here's an example image showcasing the current positioning that I aim to modify:
https://i.sstatic.net/cS8BL.jpg
The relevant section of the DOM structure appears as follows:

<div role="tooltip" class="base-Popper-root MuiDataGrid-menu css-1xif2b4-MuiPopper-root-MuiDataGrid-menu" style="position: absolute; inset: 0px 0px auto auto; margin: 0px; transform: translate3d(-915.455px, 105.455px, 0px);" data-popper-placement="bottom-end"><div class="MuiPaper-root MuiPaper-elevation MuiPaper-rounded MuiPaper-elevation1 css-1ps6pg7-MuiPaper-root" style="opacity: 1; transform: none; transform-origin: right top; transition: opacity 207ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, transform 138ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;"><ul class="MuiList-root MuiList-padding MuiDataGrid-menuList css-h4y409-MuiList-root" role="menu" tabindex="-1" id=":ru:" aria-labelledby=":rv:"><li class="MuiButtonBase-root MuiMenuItem-root MuiMenuItem-gutters MuiMenuItem-root MuiMenuItem-gutters css-1ihpxwe-MuiButtonBase-root-MuiMenuItem-root" tabindex="-1" role="menuitem"><div class="MuiListItemIcon-root css-cveggr-MuiListItemIcon-root"><svg class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-i4bv87-MuiSvgIcon-root" focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="DeleteIcon"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"></path></svg></div>Delete<span class="MuiTouchRipple-root css-8je8zh-MuiTouchRipple-root"></span></li></ul></div></div>

I tried adjusting the positioning by styling the GridActionsCellItem component without success:


const StyledGridActionsCellItem = styled(GridActionsCellItem)(() => ({
  '& .base-Popper-root': {
    offset: {
      offset: [-30, +20],
    },
  },
}));

Below is a simplified version of my code for reference:

import * as React from 'react';
import {
  DataGrid,
  GridActionsCellItem,
  GridRowId,
  GridColDef,
  GridActionsCellItemProps,
} from '@mui/x-data-grid';
import DeleteIcon from '@mui/icons-material/Delete';

import {  styled,  } from '@mui/material';

const initialRows = [
  { id: 1, name: "sd" },
  { id: 2, name: "sdds" },
  { id: 3, name: "sdds" },
];

const StyledGridActionsCellItem = styled(GridActionsCellItem)(() => ({
  '& .base-Popper-root': {
   
      offset: {
        offset: [-30, +20],
      },
   

    
  },



}));

const DeleteUserActionItem = ({
  deleteUser,
  ...props 
}: GridActionsCellItemProps & { deleteUser: () => void }) => {
  const [open, setOpen] = React.useState(false);

  return (
    <React.Fragment>
      <StyledGridActionsCellItem {...props} onClick={() => setOpen(true)
       
    }

      
     
      
      />
    
    </React.Fragment>
  );
}

type Row = (typeof initialRows)[number];

const ActionsWithModalGrid = () => {
  const [rows, setRows] = React.useState<Row[]>(initialRows);

  const deleteUser = React.useCallback(
    (id: GridRowId) => () => {
      setTimeout(() => {
        setRows((prevRows) => prevRows.filter((row) => row.id !== id));
      });
    },
    [],
  );

  const columns = React.useMemo<GridColDef<Row>[]>(
    () => [
      { field: 'name', type: 'string' },
      {
        field: 'actions',
        type: 'actions',
        width: 80,
        getActions: (params) => [
          <DeleteUserActionItem
            label="Delete"
            showInMenu
            icon={<DeleteIcon />}
            deleteUser={deleteUser(params.id)}
            closeMenuOnClick={false}
          />,
        ],
      },
    ],
    [deleteUser],
  );

  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid columns={columns} rows={rows} />
    </div>
  );
}
export default ActionsWithModalGrid;

Source: https://mui.com/x/react-data-grid/column-definition/

Despite referencing the MUI documentation, I couldn't find a resolution to my issue.

Queries:

How can I effectively adjust the positioning of GridActionsCellItem in an MUI DataGrid using the Popper component? Are there specific props or alternative methods to customize the Popper component utilized by GridActionsCellItem for positioning? Any insights or recommendations on achieving this customization would be greatly valued. Thank you!

Answer №1

The solution that resolved the issue

  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid columns={columns} rows={rows}
        slotProps={{
          basePopper: {  modifiers: [{ name: 'offset', options: { offset: [-20, -40] } }] }
        }}
      />
    </div>
  );

This answer was found in a GitHub discussion:

https://github.com/mui/mui-x/issues/4495

Hello, you are correct in assuming that the menu components like popper are rendered outside of the grid. Therefore, applying CSS to the grid root element will not impact them as they are not direct children.

If you need to customize how items are displayed, you can use sx props on GridActionsCellItem directly.

To customize the parent list, you can pass props to the popper component using componentsProps.basePopper

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

The React OnClick and onTouchStart event handlers are functioning properly on a desktop browser's mobile simulator, but they are not responsive when

I added a basic button tag to my next.js main page.js file that triggers an alert when clicked. Surprisingly, the onClick function is functional on desktop browsers but fails to work on any mobile browser. "use client"; export default function P ...

Encountering issues when attempting to render a function within the render method in React

When attempting to render the gridWithNode function inside the render method, I encountered an error message stating: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant ...

Having trouble with React Router 4 in a subfolder?

import { BrowserRouter as Router, Route } from 'react-router-dom' <Router> <switch> <Route exact path='/' component={main} /> <Route path='/build/signup' component={SignUp} /> </swit ...

Guide to effortlessly convert SCSS to CSS using an automatic vendor prefixer

Is there a tool that can convert SCSS to CSS while automatically adding vendor prefixes? I've tried using node-sass with npm, which worked well, but it doesn't add prefixes like box-sing: border-box; or display: flex; properties. Note: I also tr ...

Using React with Redux, implement a router saga that is integrated with material-ui tabs to reflect the

As a newcomer to react, I am currently utilizing react-boilerplate along with material-ui In my project, I have tabs structured like this: https://i.sstatic.net/JiqGO.png My goal is to implement functionality where changing the current tab will also upda ...

Using Bootstrap to create a floating image amidst surrounding elements

<div id="wrapper"> <div class="row"> <div class="col-sm-6 col-xs-12 image">Image</div> <div class="col-sm-6 col-xs-12 title">Title</div> <div class="col-sm-6 col-xs-12 description"> Desc ...

How come the subitems of a second-level nested list do not appear when hovering over a hyperlink?

Show "News" in French when hovering over the French option. ul#topmenu li a#HyperLink:hover ul { background-color: pink; display: list-item; } <ul id="topmenu"> <li class="langHorzMenu"> <a href="#" id="HyperLink">French</ ...

Saving fonts when deploying on Vercel with Next.js is not supported

Troubleshooting Differences in Local Viewing and Deployment: https://i.stack.imgur.com/jktPN.png When viewing locally, everything appears as expected. However, upon deploying, there are noticeable discrepancies. https://i.stack.imgur.com/NKQQ6.png Even ...

- Utilize bullet points to exhibit keywords within a D3.js div by appending them

I'm looking to showcase the comma-separated values from a JSON file as a list in a mouseover tooltip on each node. Here is my current code snippet: div.append("div") .attr("class", "tooltip") .style("opacity", 1) .html("Node name : " + d.NodeName + ...

What is the best way to showcase a bootstrap card in a horizontal layout using Jinja 2 and a for loop

I'm facing a challenge in showing bootstrap cards in a horizontal layout instead of the default vertical arrangement using a for each loop. Below is the code snippet: <div class="row"> <div class="col-lg-12"> {% for game i ...

It is not possible to alter the styles of the ng-daterangepicker Angular plugin

After installing the angular2 plugin "ng-daterangepicker", I attempted to resize a div within it by modifying the .sass file. However, despite clearing the cache, the changes did not reflect in my browser. It seems that I may need to make adjustments to .s ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

React: Struggling to configure proxy servers on a React application

After attempting to add a proxy to the package.json of my own React app, I encountered some issues with it not functioning correctly. Interestingly, the basic create-react-app example worked flawlessly even though it lacked any webpack configuration. Belo ...

Troubleshooting Bootstrap image alignment problem with columns on extra small screens

My website showcases screenshots of my software in a div element. Everything looks great on larger screens, but once I switch to a phone or resize the window, the images don't align properly, leaving empty space. Refer to the image below for clarifica ...

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

function to choose in antd datepicker component

Is there a way to obtain the currently selected date within the onSelect function after updating the selected date in the state? onSelect = (cal) => { this.setState({ selectedValue: cal }); alert(this.state.selectedValue); After making ...

Tips for positioning a 404 message at the center of a webpage

Struggling with centering a 404 error message on your Bootstrap 5 page without messing up the footer layout? When the viewport is small, the 404 message may end up getting covered by the footer. Feel free to check out the code snippet in full view to see ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

A CSS class that inherits properties from another class

I have a simple question that I can't seem to find any documentation on the internet for. It's possible that my search terms were not quite right... Let's consider a CSS class called centered, which centers elements and performs other actio ...

Is there a way to display a vertical list in a horizontal orientation?

I am in the process of creating my portfolio on Cargo Collective and have customized one of their pre-made themes to suit my preferences. The only thing I'm currently struggling with is how to change a set of vertical links to display horizontally ins ...