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

Using webapp2 to serve a stylesheet in a non-Google App Engine environment

After successfully deploying an app using webapp2/jinja2 and a Paste server, I encountered difficulties serving static stylesheets. I managed to access static files by following this method. Additionally, I implemented a StaticFileHandler that I discovere ...

:after pseudo-element along with HTML tags

I have recently designed a basic webpage in an attempt to simulate ajax using CSS. In order to achieve this, I aimed to create hidden radio buttons with visible labels, and load an external CSS file when the user clicks on a label. However, I encountered o ...

The dropdown menu component in ReactJS is malfunctioning

I'm currently working on a form that includes a select box which fetches data from the server and posts it back to the same server. I have implemented the select box component from ant design. Unfortunately, I've encountered an issue with the ha ...

Error encountered: MUI: The export of withStyles from @mui/material/styles is now unavailable

import { styles } from '@mui/material/styles' I'm trying to utilize the styles feature from material-ui in my React application. However, I encountered an error message in the console. Uncaught Error: MUI: withStyles is no longer exported f ...

"Execute the build command for a create-react-app project with Material

I am using create-react-app along with material-ui@next When I ran yarn build, I encountered an error An error occurred while trying to minify the code in this file: ./node_modules/material-ui/es/Typography/Typography.js For more information, please visi ...

Refreshing an application programmatically in React Native when signing in or out: A guide

Utilizing Expo and React Native in my app, I have successfully integrated authentication using Firebase. However, I am encountering an issue where the navigation stack does not refresh when signing in or out. The only way to trigger a change is by making ...

The descendant selector in CSS fails to apply changes to the element

I am struggling to modify the border of a specific descendant element and so far I have not been successful. Despite using the correct descendant selector in the HTML below, the style change is not taking effect. If anyone has any insights on what could be ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

Issue with rendering the search component due to a conflict with validate.js

I am currently facing an issue with my search component that includes validation using JavaScript. The problem I am encountering is that when I first focus on the input, the validation and request do not work. However, after losing focus on the input, cli ...

Issue with resetting input forms in ReactJS

I have a simple form that seems to be clearing the rest of the fields every time I try to fill it. Additionally, validation errors are being displayed below each field instead of just one. How can this issue be fixed? Here is how the form looks before any ...

Scroll to the top of jQuery DataTables when clicking pages in a random order from the bottom to the top and

In my current project, I am working with jQuery Datatables and I need to customize its default behavior. Currently, when I navigate to page 61, the page scroll remains at the bottom of the page. However, if I then click on a lower page number like 60, th ...

Trouble arises when implementing personalized buttons on the Slick JS slider

Are you struggling to customize buttons for your Slick Slider JS? I am facing a similar issue with applying my own button styles to the slider. I am interested in using arrow icons instead of the default buttons. Here is the HTML code snippet: <secti ...

Incorporating Material-UI with external third-party React elements

What is the best approach for styling third-party components like react-paginate using Material-UI elements (such as bars and buttons)? Is this achievable? ...

Trouble with displaying list bullets in jQTouch framework

I'm currently experimenting with jQTouch for a web app designed for iPhones. However, I am facing an issue where I want the content on the pages to display normal bullet lists instead of being styled as bars in the jqt theme. To achieve this, I am att ...

Generate a variety of requests with Axios

I have a task where I need to send multiple Axios requests, but the number of requests can be completely random. It could range from 0 to even millions. Once all the requests are completed, I then need to perform an action, such as updating my state, which ...

The component is not receiving any props

In my house component, I retrieve a user's name and then verify its validity (using axios to check if the name is correct). If the name is valid and I click the button, I intend to display the Dashboard component. However, the issue arises when even a ...

An error pops up in my dialog box whenever I try to click on it

When I click on the mail icon, I want to open a dialog. However, although everything seems to be working fine, I am encountering an error in the console: index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of ...

Aligning the Bootstrap 5 Accordion Button in the Center and Adding Line Breaks

I have a few queries regarding the code I am implementing using Bootstrap 5. JSFiddle How can I center align the header within the button? <button class="accordion-button collapsed text-center" type="button" data-bs-toggle=" ...

Troubleshooting problem with Vuetify's parallax fluid template

In my quest to implement a fluid template for responsive design viewports, I encountered an issue. The layout looks good on medium viewports (md) but fails to scale correctly on smaller viewports (sm or xs). This is because the height of the parallax backg ...

varying perspectives in different browsers within my React application

I'm experiencing inconsistencies in the appearance of my website when viewed on Chrome mobile compared to Safari on an actual phone. Despite using prefixes for all my styles (WebKit, etc.) and incorporating normalize.css to address any issues, the dis ...