How can the height of a Material-UI Grid item be dynamically set to match its width?

I am trying to create grid items that are square, where the height matches the width:

const App = ({ width, items }) => (
  <Grid container>
    {items.map((v) => (
      <Grid item md={width}> // I want this Grid item to be square
        v
      </Grid>
    ))}
  </Grid>
);

How can I achieve this? note: width varies.

Answer №1

If I were approaching this layout, my preference would be to utilize CSS Grid. However, should you opt for the Material UI Grid components, it seems necessary to work with properties like paddingBottom: '100%' and experiment with absolute positioning techniques.

For a visual representation, check out this example: https://codesandbox.io/s/stack-overflow-square-grid-using-mui-cy4p5

Answer №2

As per the information provided on material ui grid

achieving a square box is made simple and easy. Make sure to review the code snippets below:

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    height: 100,

    width: 100,
  },
  control: {
    padding: theme.spacing(2),
  },
}));

export default function SpacingGrid() {
  const [spacing, setSpacing] = React.useState(2);
  const classes = useStyles();

  const handleChange = (event) => {
    setSpacing(Number(event.target.value));
  };

  return (
    <Grid container className={classes.root} spacing={2}>
      <Grid item xs={12}>
        <Grid container justify="center" spacing={spacing}>
          {[0, 1, 2].map((value) => (
            <Grid key={value} item>
              <Paper className={classes.paper} />
            </Grid>
          ))}
        </Grid>
      </Grid>
      <Grid item xs={12}>
        <Paper className={classes.control}>
          <Grid container>
            <Grid item>
              <FormLabel>spacing</FormLabel>
              <RadioGroup
                name="spacing"
                aria-label="spacing"
                value={spacing.toString()}
                onChange={handleChange}
                row
              >
                {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((value) => (
                  <FormControlLabel
                    key={value}
                    value={value.toString()}
                    control={<Radio />}
                    label={value.toString()}
                  />
                ))}
              </RadioGroup>
            </Grid>
          </Grid>
        </Paper>
      </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

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...

Combining HTML, CSS, and ASP.NET is a

<table cellspacing="0" cellpadding="0" width="100%" style="background-image: url('/ProjectSample/images/LoginBox.png'); background-repeat: no-repeat;"> Is there something incorrect with the way this style tag is referencing an image with ...

What causes npm to be undefined when I verify node?

screenshot of my terminal Currently learning react and encountered an issue while checking if npm downloaded properly. It appears to be running fine, but for some reason, after I enter 'node' and then try to check npm again, I get an error messa ...

instantaneous MUI export with just a single click

Greetings MUI datagrid react enthusiasts! I've managed to disable both CSV and print options, leaving only Excel. However, exporting to Excel now requires two clicks - one to show the dropdown and another to select export excel. Is there a way to make ...

Minimize the screen dimensions and adjust the margins accordingly

Having a problem with responsive margins? Take a look at this site as an example: When I shrink the screen size, the margins decrease and smoothly transition from 4 to 2 columns. In my case, it does something similar but the issue is that the margin does ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

Removing background color and opacity with JavaScript

Is there a way to eliminate the background-color and opacity attributes using JavaScript exclusively (without relying on jQuery)? I attempted the following: document.getElementById('darkOverlay').style.removeProperty("background-color"); docume ...

Obtaining the current timestamp from Firebase Firestore in a React application

In the project I'm currently working on, I am utilizing Firebase Firestore database. To add documents from my front-end React application, I require the current timestamp. import * as firebase from "firebase"; import React, {useState} from & ...

What is the best way to apply a unique style (such as adding a bottom border) to all list items

Currently, I am utilizing React Material components with a List that is internally represented as ul li elements. My goal is to apply a style to all li elements by adding a bottom border. One approach is to include the className={classes.sideBar__listItem_ ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Why won't my sticky element function properly with the position attribute set to sticky?

Hey there! I've been diving into learning all about CSS positions and have nailed down most of them. However, for some reason, the sticky position just won't cooperate and is stubbornly acting like a relative one instead. Check out my HTML snipp ...

Encountered an unexpected symbol < in JSON while implementing fetch() operation

I'm currently working on linking my React signup page to my Django API in order to automatically create a user profile in Django when a user signs up. Whenever I attempt to create a new user, I encounter this error in my console: Signup.js:33 ...

Deactivate a div based on a Razor variable in ASP.NET MVC4

Is there a secure method to disable a div based on a Razor variable in ASP.NET MVC 4.0? I attempted using a CSS class, but it was easily bypassed with developer tools. .disableddiv { pointer-events: none; opacity: 0.4; } Any advice on how to effectively ...

The alignment of the background images is off

I am attempting to give a container a background image and then create two div tags using the col-md-6 classes from Bootstrap. The main div's background image is of grass texture, while the two inner divs have a skeleton of a football court as their b ...

Modifying the input type of Material-UI TextField to only accept numbers

Currently, the TextField Material-UI with type = "number" accepts numbers (0-9), comma (,), and double dash(--) However, I only require a single dash(-) I have tried inserting a pattern in inputProps, but it does not seem to work Any assistanc ...

Strapi's URL for password recovery at '/forgot-password' is resulting in an error code 400

I'm encountering an issue while trying to set up the password recovery feature on my strapi application. Despite following the documentation instructions, the network request using the code below: axios.post('http://localhost:1337/auth/forgot-pa ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

Animation failing to be queued properly

Here is a snippet of code that moves a heading icon back and forth when you hover over the heading: jQuery('h1.heading').hover( function(){ $icon = jQuery('.heading-icon', this); if( ! $icon.is(':animated') ){ ...

Changes in state do not reflect updates to the React styling

I'm experiencing issues with a simple React element that should adjust its style based on screen size, but for some reason, it's not updating as expected. Check out the code snippet below: export class DashboardHContainer extends Component { c ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...