Achieving alignment of items within nested Grid components in React Material UI

Currently, I am working on building a web page using the React Material UI Grid component. However, I'm encountering an issue with aligning items across nested grids. The current view looks like this: https://i.sstatic.net/bUreX.png

What I want is for the item on the right half side to stretch and align with the left half side at the bottom, creating an ideal layout like this: https://i.sstatic.net/SpevP.png

Here is the relevant code snippet:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';

const useStyles = makeStyles((theme) => ({

  paper: {
    padding: theme.spacing(1),
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
}));

export default function NestedGrid() {
  const classes = useStyles();

  function FormRow3() {
    return (
      <React.Fragment>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
      </React.Fragment>
    );
  }
  function FormRow2() {
    return (
      <React.Fragment>
        <Grid item xs={12}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
      </React.Fragment>
    );
  }

  return (
    <div >
      <Grid container spacing={1}>
        <Grid container item xs={6} spacing={3}>
          <FormRow3 />
          <FormRow3 />
        </Grid>
        <Grid container item xs={6} spacing={3}>
          <FormRow2 />
        </Grid>
      </Grid>
    </div>
  );
}

For further reference, I have provided a sandbox link here: https://codesandbox.io/s/material-demo-forked-xunx7

If anyone can provide assistance, it would be greatly appreciated.

Edit: With the use of @nipuna777's solution (flex=1), I was able to align the items in the grid. However, in more complex scenarios like this one: https://i.sstatic.net/zsSNE.png

The top, bottom, and right parts may not align perfectly. How can I ensure that all these boundaries align perfectly? Any guidance on this matter would be helpful.

Here is the code for the aforementioned scenario: https://codesandbox.io/s/material-demo-forked-imrrh?file=/demo.js

Answer №1

Here is a potential solution that involves making the following adjustments:

  1. Include container={true} within the Grid element to establish a flex container for the child components. In this scenario, the child components consist of Paper.
<Grid item xs={12} container={true}>
  <Paper className={classes.paper}>item</Paper>
</Grid>
  1. To the classes.paper definition, append flex: 1 to guarantee that the Paper element occupies the entire space within the container.
paper: {
  flex: 1,
  padding: theme.spacing(1),
  textAlign: "center",
  color: theme.palette.text.secondary
}

For a demonstration, refer to the following example: https://codesandbox.io/s/material-demo-forked-ud6um?file=/demo.js

Answer №2

Have you attempted to decrease the spacing of the central Grid to 2?

return (
    <div>
      <Grid container spacing={1}>
        <Grid container item xs={6} spacing={3}>
          <FormRow1 />
          <FormRow3 />
        </Grid>
        <Grid container item xs={6} spacing={2}>
          <FormRow2 />
        </Grid>
        <Grid item xs={12} spacing={3}>
          <FormRow4 />
        </Grid>
      </Grid>
    </div>
  );

Due to the limitation on the amount of code that can be posted in comments, I opted to provide this solution as an answer instead.

Answer №3

Upon inspecting the code, it appears that the issue lies in having a padding applied instead of setting the height.

<div class="MuiPaper-root makeStyles-paper-1 MuiPaper-elevation1 MuiPaper-rounded">
 item
</div>

To rectify this, simply replace padding: 8px; with height: 100%;

You can then utilize the available classes in the element above to implement the new style effectively.

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

How can I place a div using pixel positioning while still allowing it to occupy space as if it were absolutely positioned?

I successfully created an slds path element with multiple steps. I want to display additional subtext information below each current step, but there might not always be subtext for every step. To achieve this, I created an absolute positioned div containi ...

The user fails to be redirected following wallet authentication in NextJS

Can someone help me figure out how to redirect the user to the onboard page after successfully connecting to their wallet? Web3Button doesn't seem to be returning anything and I'm stuck. import React, { useEffect } from "react"; import ...

Troubleshooting puppeteer PDF: Unable to set table height using CSS for tr:last-child { height: 100%; }

My Node.js code snippet is as follows: await page.setContent(html, {waitUntil: 'networkidle2'}); const pdf = await page.pdf({ format: 'A4', printBackground: true, margin: { top: '14mm', // default is 0, units: mm, c ...

Padding causing links to break exclusively in Firefox

As a seasoned front-end developer, I recently encountered an issue that has stumped me. My main navigation bar has extensive right padding to ensure the hover dropdowns have ample space. The problem seems to be in this piece of code: HTML: <div id="h ...

Looking for help in resolving console error displaying 'Uncaught (in promise)' notification

I've encountered an issue while trying to troubleshoot a problem that involves using the find() method, which is causing an error. import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstant'; const cartReducers = (state = { ...

What is the best way to position a Button on the far right of an MUI AppBar?

I'm struggling to grasp the concept of aligning items in MUI. Here is my code snippet: class SignUpForm extends React.Component { render() { return ( <Button sx={{ justifyContent: "flex-end" }} colo ...

Button for searching through the Bootstrap navigation bar

I'm currently working on adding a search menu to the navbar in two different designs - one for screens below 767px and another for screens above 767px. Although I have been successful in expanding the search bar, I am facing issues with the correct p ...

Discover the method for retrieving the value of a toggle-style checkbox

I am currently working with a toggle switch checkbox and I need to extract its value using JavaScript or jQuery when the state changes. Based on this value, I aim to highlight the text of the label associated with the toggle switch, whether it's opti ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

Rearranging the @use directive in Sass

Here are some style snippets: tokens.scss .text-center { text-align:center; } .bold { font-weight: bold; } @mixin text-style-1 { font-size: 1.2rem; font-weight: bold; } component/card.scss @use "../token.scss" as tokens; .card { @i ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

Replicate and launch React Native projects directly from GitHub

I have been attempting to develop and launch a react native application on my phone. I followed the instructions in the Getting Started guide and everything seemed to be working smoothly. Here is what I did to run it: cd AwesomeProject react-native start ...

Arranging Bootstrap Grids within Laravel

On my current web page, I have implemented Bootstrap Grids as seen in the image below. Check out My Bootstrap Grid Layout However, I am aiming to achieve a grid layout similar to the one shown in the picture with a red indicator. Here is the Desired Boo ...

Center align Bootstrap 4 dropdown menu

I am attempting to center align my dropdown menu using Bootstrap 4. Following the given example: [ This is the result I am achieving: [ This is the code I have implemented: <div class="container"> <div class="row"> <div class=" ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

Resolving CSS Conflict in Panels with Legacy Bootstrap

I have recently implemented Panels from Bootstrap 3 with the older version of Twitter-Bootstrap. My challenge lies in adding the well class to the panel body, as it results in excessive padding. This was not an issue when using BS3, leading me to believe ...

Transferring information from one page to the next

How can I efficiently transfer a large amount of user-filled data, including images, between pages in Next.js? I've searched through the Next.js documentation, but haven't found a solution yet. ...

Tips for customizing the jQuery countdown styling

Currently, I have incorporated the jQuery countdown into my project which consists of solely the essential Javascript required for the countdown to function. However, I am interested in achieving a similar visually appealing "animated" style similar to t ...

Sort your list efficiently with a custom hook in React using Typescript

I've been working on developing a custom hook in React that sorts an array based on two arguments: the list itself and a string representing the key to sort by. Despite trying various approaches, I haven't been able to find a solution yet. I&apos ...