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

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

Tips for retrieving the selected item from Material-UI DropDownMenu

Hello fellow StackOverFlow users, I am new here so please be patient with me In my React app, I am using Material-UI's DropDownMenu to collect information from users. However, the issue I'm facing is that the value being pushed to state is an in ...

Invoke a function within an HTML element inserted using the html() method

Looking for help with a JavaScript function: function toggle_concessions(concessions) { var text = "<table>"+ "<tr><td class='concession-name'>gfhgfbfghfd</td><td class='op-encours&a ...

Vue JSON Response Guide

Inquiry from a beginner. My goal is to display the name of a city using props. When I use {{ props.feed.location }} to fetch: { "latitude": 50.85, "longitude": 4.35, "name": "Brussels, Belgium", "id": 213633143 } However, when I attempt {{ props.feed.l ...

Uploading an image along with additional information to Strapi using React

Can you assist me with allowing users to post data on Strapi, such as their name, URL, description, and image? I attempted to add an input type file but encountered a 500 error. I suspect this could be due to the need to call localhost:1337/upload, but I& ...

Switch between light and dark modes with this attractive Radix UI and Next.js toggle feature

Currently, I am working on incorporating a light versus dark mode toggle for my Next.js application. To style my app, I have opted to use the radix UI component library. However, I find myself in need of assistance when it comes to determining the logic re ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

React component not rendering in Django template

After ensuring that I have all the necessary packages installed and confirming that my webpack configuration is set up correctly, I am able to run the server and dev script without encountering any errors. However, when I add any content (such as text) to ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this function ...

Having difficulty building a react.js application using Visual Studio 2019

Currently, I am following a helpful tutorial on creating a react.js application using visual studio. At this stage, the tutorial instructs me to open the command prompt and enter the following command: webpack app.tsx --config webpack-config.js (I have ...

Steps to alter background image and adjust its height upon function activation

I am working on a search page with an advanced search option that only certain users can access. I need the height of my div to increase accordingly and also change the background image to a larger size when the advanced search is selected. How can I make ...

Creating React elements dynamically with material-ui can be done by utilizing state expressions in properties. This allows for the generation

Within a functional component, I aim to dynamically generate material-ui context menus by utilizing a state object: let legendContextMenuStatesObject = {}; for (let key of keys) { legendContextMenuStatesObject[key] = initialState; } const [lege ...

Does ng-include fetch the included HTML files individually or merge them into a single HTML file before serving?

Is there a performance impact when using the ng-include Angular directive, in terms of having included HTML files downloaded as separate entities to the user's browsers? I am utilizing a CDN like AWS CloudFront instead of a node server to serve the H ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

What is the most efficient method for transferring session data from a Client component to a server component in NEXT.js version 13 and beyond?

Currently, I am working on a web application that requires passing session?.user?.email from the useSession() function in next-auth/react to a server-side component. This server-side component will then execute a fetch request to /api/users/email/ to deter ...

Create a dynamic dropdown menu that adjusts its options based on the number of items in an

If I have an array like this: const foodArray = ["pizza","pasta","sushi"] I attempted to create a dropdown menu based on the number of elements in the array, using the following code: <FormControl className={classes.formCo ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...