Issue with implementing MUI Grid within a dialog across various screen sizes

While working with a MUI dialog and MUI grid, I encountered an issue. The code I am using is directly from the website, with only minor modifications to the dialog function names and the box wrapping the dialog. Despite changing the size of the dialog, the grid items continue to display in a three-column layout instead of stacking to 12 at 'xs' screen size. I can't seem to figure out why this is happening as the code seems correct to me.

      <Box sx={{flexGrow: 1}}>

        <Dialog
          fullWidth={fullWidth}
          maxWidth={maxWidth}
          open={openDialog}
          onClose={handleCloseDialog}
        >
          <DialogTitle>Optional sizes</DialogTitle>
          <DialogContent>
            <DialogContentText>
              You can set my maximum width and whether to adapt or not.
            </DialogContentText>
            <Box
              noValidate
              component="form"
              sx={{
                display: 'flex',
                flexDirection: 'column',
                m: 'auto',
                width: 'fit-content',
              }}
            >
              <FormControl sx={{ mt: 2, minWidth: 120 }}>
                <InputLabel htmlFor="max-width">maxWidth</InputLabel>
                <Select
                  autoFocus
                  value={maxWidth}
                  onChange={handleMaxWidthChange}
                  label="maxWidth"
                  inputProps={{
                    name: 'max-width',
                    id: 'max-width',
                  }}
                >
                  <MenuItem value={false}>false</MenuItem>
                  <MenuItem value="xs">xs</MenuItem>
                  <MenuItem value="sm">sm</MenuItem>
                  <MenuItem value="md">md</MenuItem>
                  <MenuItem value="lg">lg</MenuItem>
                  <MenuItem value="xl">xl</MenuItem>
                </Select>
              </FormControl>
              <FormControlLabel
                sx={{ mt: 1 }}
                control={
                  <Switch checked={fullWidth} onChange={handleFullWidthChange} />
                }
                label="Full width"
              />
            </Box>
            <Grid container>
              <Box sx={{ flexGrow: 1 }}>
                <Grid container spacing={{ xs: 2, md: 3 }}>
                  {Array.from(Array(6)).map((_, index) => (
                    <Grid item xs={12} sm={4} md={4} key={index}>
                      <Item>xs=2</Item>
                    </Grid>
                  ))}
                </Grid>
              </Box>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseDialog}>Close</Button>
          </DialogActions>
        </Dialog>

Answer №1

It appears that the reason for this behavior is due to the Grid adjusting its layout based on responsive breakpoints of the viewport, rather than the container width. In the code provided, the Grid should transition to a single column when the window is resized below sm, which is 600px.

If the intention is to simulate the responsive sizes, perhaps for a demonstration, it may be advisable for the Grid to calculate values based on conditions derived from the specified maxWidth and fullWidth, as opposed to the actual viewport width.

View the minimized demo at: Stackblitz (may require opening in a new tab to see changes).

<Grid container spacing={{ xs: 2, md: 3 }}>
  {Array.from(Array(6)).map((_, index) => {
    const responsive = { xs: 12, sm: 4, md: 4, lg: 2, xl: 2 };
    const selected = responsive[`${maxWidth}`] || 0;
    const mockedResponsive = Object.keys(responsive).reduce(
      (acc, cur) =>
        !fullWidth
          ? {
              ...acc,
              [cur]: Math.max(
                responsive[cur],
                Math.max(selected, responsive["md"])
              ),
            }
          : { ...acc, [cur]: Math.max(responsive[cur], selected) },
      {}
    );
    return (
      <Grid item key={index} {...mockedResponsive}>
        <Typography>xs=2</Typography>
      </Grid>
    );
  })}
</Grid>

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

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

Error displaying React components using Webpack

Just diving into the world of React and decided to enroll in a course on Udemy React.js Essential Training However, I quickly realized that the tutorials are a bit outdated. As I was following along, I encountered an error while trying to compile my c ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

combine two separate typescript declaration files into a single package

Can anyone help me figure out how to merge two typescript definition packages, @types/package-a and @types/package-b, into one definition package? package-a.d.ts [export package-a {...}] package-b.d.ts [exports package-b {...}] package-mine.d.ts [ export ...

Inline CSS alignment

While experimenting with layout inline elements, I came across some unusual behavior. Can someone please explain why there is a difference? I have applied the following CSS to both HTML structures: .time { position: relative; top:100px; heigh ...

Automatically synchronize dynatable with AJAX requests and JSON responses

I'm currently facing a bit of confusion as my code appears to be functioning properly, but the table is not updating as expected. xD I am fetching data from my database and loading it into a table, aiming for it to automatically update every three se ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

What are the solutions for resolving problems with the display and functionality of a multi-page form in Internet Explorer?

I am currently working on a form and you can view it at this link: http://jsfiddle.net/pPWr3/14/ While the form displays correctly in Chrome and Firefox, I am experiencing display and functionality issues when using Internet Explorer 9. The problems inclu ...

Issues with Material-UI React components functionality

I recently discovered http://www.material-ui.com/ for front end design and decided to give it a try by following the getting started tutorial. I created an HTML file with the following code : <!DOCTYPE html> <html> <head> <meta ch ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

Tips for hiding text on hover effect

I'm currently working on a menu where each item displays text that is replaced by an email address on hover. However, I am struggling to remove the text during the hover state. Below is the code I have written so far: #home { font: 30px 'Le ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

Resolved issue with sticky header movement after scrolling event

I've been working on a sticky header code, but I'm having trouble achieving a smooth scroll transition. The fixed header seems to jump after just one scroll. Here is the basic HTML structure: <div class="headerWrapper"> <div id="to ...

What steps should I take to fix the issue of "[ERR_REQUIRE_ESM]: Must use import to load ES Module" while working with D3.js version 7.0.0 and Next.js version 11.0.1?

Encountered a roadblock while integrating D3 with Next.js - facing an error when using D3.js v7.0.0 with Next.js v11.0.1: [ERR_REQUIRE_ESM]: Must use import to load ES Module Tried utilizing next-transpile-modules without success Managed to make D3.js ...

Creating a triangle shape using Bootstrap to style a div element, similar to the image provided

Trying to achieve the look of the attached image with a few divs. I know I can use a background image like this: background:url(image.png) no-repeat left top; But I'm curious if there's another way to achieve this without using a background ima ...

Is it possible to establish a connection between React and a MySQL Database?

I've been encountering issues with connecting to a remote database in React. Despite my efforts, I haven't been successful in establishing the connection. I have tried various solutions without any luck. The goal is simple - I just want to connec ...

Vercel deployment causing issues with Tailwind CSS functionality post deployment

I've encountered an issue with Tailwind CSS styling in my web app. While everything looks perfect on my local machine, once I deploy the project on Vercel from my GitHub repository, the styling breaks. Any idea what could be causing this problem? Her ...