Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component to achieve this layout as shown in the image attached. Below is the structure of the parent and child components involved:

Parent Component:

<StyledDialogFooter sx={{ padding: 0, pt: 2 }}>
            {(secondaryButtonProps || secondaryButton) && (
              <Button
                variant="contained"
                color="secondary" 
                size="small"
                {...secondaryButtonProps}
                onClick={debouncedSecondaryClick}
                data-testid={noButtonTestId}
              >
                {secondaryButtonProps?.children ?? 'No'}
              </Button>
            )}
            {(primaryButtonProps || primaryButton) && (
              <Button
                variant="contained"
                color="primary"
                size="small"
                {...primaryButtonProps}
                onClick={debouncedPrimaryClick}
                data-testid={yesButtonTestId}
              >
                {primaryButtonProps?.children ?? 'Yes'}
              </Button>
            )}
          </StyledDialogFooter>

Child Component:

<Dialog
      open={open}
      loading={waitingForResponse}
      title={'Manage sharing'}
      onClose={onClose}
      paperSx={{ width: '380px !important' }}
      primaryButton
      primaryButtonProps={{
        onClick: onSave,
        variant: 'contained',
        color: 'primary',
        children: 'Save',
        disabled: saveButtonDisabled,
        sx: {
          ...(breakpoint === 'sm' && {
            width: '100%',
            display: 'block',
          }),
        },
      }}
      secondaryButton
      secondaryButtonProps={{
        onClick: onCancel,
        variant: 'contained',
        color: 'secondary',
        children: 'Cancel',
        sx: {
          ...(breakpoint === 'sm' && {
            width: '100%',
            display: 'block',
          }),
        },
      }}
    >

Despite trying to apply custom CSS using the sx prop, the buttons still appear side by side instead of stacked. Any suggestions on how to successfully override this? Refer to the following images for clarification:

Current Layout: https://i.stack.imgur.com/IOhi5.png

Answer №1

When thinking about how to approach this, the first thing that comes to mind is utilizing Grid.

Instead of relying on MUI Grid, it's worth investing time in understanding the CSS solution for grid layout, as it offers more flexibility and control.

In my experience, combining MUI breakpoints with standard CSS grid has been quite useful:

<Dialog>
      <DialogContent>
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: "repeat(12, 1fr)",
            gap: 2,
          }}
        >
          <Button
            sx={{
              gridColumn: {
                xs: "span 12",
                sm: "span 12",
                md: "span 6",
                lg: "span 6",
                xl: "span 6",
              },
            }}
          >
            Button_1
          </Button>
          <Button
            sx={{
              gridColumn: {
                xs: "span 12",
                sm: "span 12",
                md: "span 6",
                lg: "span 6",
                xl: "span 6",
              },
            }}
          >
            Button_1
          </Button>
        </Box>
      </DialogContent>
    </Dialog>

By applying Grid to the MUI box, you can easily utilize MUI breakpoints to adjust button widths effectively on different screen sizes like xs and sm. It's always beneficial to delve deeper into Grid layout techniques, as they can greatly simplify the process of creating complex layouts.

Answer №2

To enhance your layout, consider using the Stack component:

<Stack
  direction={{ xs: 'column', sm: 'row' }}
  spacing={{ xs: 1, sm: 2, md: 4 }}
>
  <Button>Button 1</Button>
  <Button>Button 2</Button>
  <Button>Button 3</Button>
</Stack>

You can replace each Item with a Button or any other desired Component.

Answer №3

If you're looking to customize the appearance of your buttons in material-ui, consider placing them within a Stack component instead of altering their behavior directly. By using a Stack component, you can easily adjust the layout based on different screen sizes. Here's an example:

<Stack spacing={2} direction={{xs: 'column', sm: 'row', md: 'row'}}>
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</Stack>

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

What is the best approach to implementing React Hooks in Typescript when using Context?

I have implemented the following code snippet in my new React Native project to enable Dark Mode using TailwindCSS: import React, { createContext, useState, useContext } from 'react'; import { Appearance } from 'react-native'; import { ...

"Enhance Your Website with Custom jQuery Preloaders

Currently, I am facing a challenge while developing a website. Specifically, I am struggling with resolving the issue of a blank page being displayed. The website that I am working on involves functionality where swiping right triggers data insertion into ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

The issue with text color not displaying properly within a Material-UI Theme

While designing a color theme using Material-UI, I specified the contrast text as white (#fff). Surprisingly, it seems to work for buttons with the primary color but not for those with the secondary color. I attempted overrides following the suggestions p ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Why is the jQuery not functioning within the AngularJS function?

I am encountering an issue with writing jQuery inside an AngularJS function. I can't seem to figure out why it's not working properly. HTML <div> <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showD ...

The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details p ...

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...

Update and swap out outdated material

Struggling with replacing old content in a div after using AJAX. The issue is that both the new and old content are appearing inside the div. Here is my current Ajax code: $('#vu').on("click", function(e){ $.ajax({ url: 'url to pag ...

Disable image loading for users who have javascript enabled

I find myself caught in a chicken-egg dilemma. The webpage I created contains numerous images that need to be loaded, and so I implemented a script that loads images as the user scrolls, similar to how Facebook or Google Images functions. When the user rea ...

reloading a URL dynamically using an array in JavaScript

I need assistance with a Chrome extension code. The goal is to have it check the page that initially loads, and if it matches my website st.mywebsite.com, execute the specified code. Currently, it does not perform this check and runs on every loaded page ...

How does the const primary = red[500]; // #F44336 differ from const accent = red['A200']; // #F44336?

Here are three ways to retrieve color: const primary = red[500]; // #F44336 const accent = purple['A200']; // #E040FB const accent = purple.A200; // #E040FB (alternative approach) However, I am unsure of the distinctions between them and whic ...

Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria: Characters Used Password Strength Length ABC abc 123 #$& WEAK ... 1 x ...

Ensure Mantine in React application is configured to exclusively utilize the dark theme

Currently, I am developing a basic web application in React and incorporating Mantine (v6.0.19) as my component library. My objective is to ensure that the dark theme of MantineProvider remains constant, irrespective of the user's browser theme settin ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

A guide on updating a JSON object based on specific criteria

I'm dealing with two JSON files here - the first one is named origin.json, and the second one is called newData.json. My goal is to update the child value of Origin based on the data in NewData. However, I only want this update to impact items that a ...

Extract data from a JSON object and connect it to input fields on a form

I am currently working with a large JSON object that I need to parse and bind to various form fields. Here is a snippet of the code, but you can view the entire code here. The main question I have is what would be the most efficient way to achieve this? Wo ...

What steps can be taken to resolve the delay in transition when clicking on "read less

I implemented a transition effect for the Read More and Read Less buttons, however, there seems to be a delay on the transition when clicking on the Read Less button. This delay was not intentionally set by me. How can I resolve this issue and also apply a ...