Categories
React Answers

How to add 2 Papers side by side in a React Material-UI Grid?

Spread the love

Sometimes, we want to add 2 Papers side by side in a React Material-UI Grid.

In this article, we’ll look at how to add 2 Papers side by side in a React Material-UI Grid.

How to add 2 Papers side by side in a React Material-UI Grid?

To add 2 Papers side by side in a React Material-UI Grid, we can add a outer Grid component with the container prop set to make it a container.

Then we can add 2 more Grids inside it to and add one Paper inside each.

For instance, we write:

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

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing * 2,
    textAlign: "center",
    color: "green"
  }
}));

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

  return (
    <div className={classes.root}>
      <Grid container spacing={24}>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

We call makeStyles with a function to style add styles for the root and paper classes.

Then we call useStyles in App to return the classes.

Next, we add the Grid with the container prop to make it a container.

Then we add 2 Grids inside to use as containers for the Paper.

We add the item prop to the Grids to make the display correctly as child elements.

They should display side by side if the screen is large and stacked when the screen is small since we set the xs and sm prop column widths.

Finally, we add the Paper in the child Grids to add our content.

Conclusion

To add 2 Papers side by side in a React Material-UI Grid, we can add a outer Grid component with the container prop set to make it a container.

Then we can add 2 more Grids inside it to and add one Paper inside each.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *