skip to Main Content

So basically I have a list of objects like this:

const objects = [{name: ‘some name’, count: ‘how many of that name’}, …]

And I’m trying to render them like this:

        {objects.map((item) => (
            <Grid item key={item.name} xs={2} style={styles.count}>
                <Typography
                    key={item.name}
                    align="right"
                    component="h1">
                    {`${item.name}: ${item.count}`}
                </Typography>
            </Grid>
        ))}

As you can imagine the result of this is something like this

name 1: 4   name 2: 4    name 3: 4
name 4: 4   name 4: 4

But I need something like this instead:

name 1: 4   name 3: 4    name 5: 4
name 2: 4   name 4: 4

3

Answers


  1. I haven’t css trick for your question. but i have a js trick and It may help you :

    const items = [
      { name: 1, count: 5 },
      { name: 2, count: 5 },
      { name: 3, count: 5 },
      { name: 4, count: 5 },
      { name: 5, count: 5 },
      { name: 6, count: 5 },
      { name: 7, count: 5 }
      ....
    ];
    
    function getColumns() {
      //get window width;
      const windowWidth = window.innerWidth;
      console.log(windowWidth);
      let columnsNumber = 3;
    
      //responsive on window width
      if (windowWidth < 400) {
        columnsNumber = 2;
      }
    
      const columns = new Array(columnsNumber);
    
      items.forEach((item, index) => {
        var columnNumber = Math.floor(index / columns.length);
        if (columns[columnNumber] === undefined) {
          columns[columnNumber] = [item];
        } else {
          columns[columnNumber].push(item);
        }
        console.log(columns);
      });
      return columns;
    }
    
    export default function App() {
      const [columns, setColumns] = useState(getColumns());
      useEffect(() => {
        window.addEventListener("resize", () => {
          setColumns(getColumns());
        });
      }, []);
      if (!columns) {
        return <h1>Loading</h1>;
      }
    
      console.log(columns);
    
      return (
        <Grid container>
          {columns.map((column, index) => (
            <Grid item key={index} xs={12/columns.length}>
              <Column items={column} />
            </Grid>
          ))}
        </Grid>
      );
    }
    
    function Column({ items }) {
      return (
        <>
          <Grid container>
            {items.map((item, index) => (
              <Grid item key={item.name} xs={12}>
                <Typography key={item.name} align="right" component="h1">
                  {`${item.name}: ${item.count}`}
                </Typography>
              </Grid>
            ))}
          </Grid>
        </>
      );
    }
    

    result of code is :

    enter image description here

    You can see domo on codesandbox

    Login or Signup to reply.
  2. Have a look through React MUI Grid-auto-flow

    Align your code and add style to parent container like this:

    <Box
      sx={{
        display: 'grid',
        gridAutoFlow: 'column',
        gridTemplateRows: 'repeat(2, 1fr)',
        gap: 1,
      }}
    >
      <Item>1</Item>
      <Item>2</Item>
      <Item>3</Item>
      <Item>4</Item>
      <Item>5</Item>
    </Box>
    

    end result shall be like this

    result

    Login or Signup to reply.
  3. modify your code to use a Grid container with multiple rows 3 columns for each

    import { Grid, Typography } from '@material-ui/core';
    
    const objects = [{name: 'some name', count: 'how many of that name'}, ...];
    
    const rows = [];
    let currentRow = [];
    for (let i = 0; i < objects.length; i++) {
      currentRow.push(objects[i]);
      if (currentRow.length === 3 || i === objects.length - 1) {
        rows.push(currentRow);
        currentRow = [];
      }
    }
    
    return (
      <Grid container spacing={2} direction="column">
        {rows.map((row, rowIndex) => (
          <Grid item container key={rowIndex} spacing={2} direction="row">
            {row.map((item, itemIndex) => (
              <Grid item key={itemIndex} xs={4} style={styles.count}>
                <Typography align="right" component="h1">
                  {`${item.name}: ${item.count}`}
                </Typography>
              </Grid>
            ))}
          </Grid>
        ))}
      </Grid>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search