Search code examples
cssreactjscss-grid

I need to have a dynamic grid like masonry grid based on scores from json


I want to display the json values into seperate grids . The height and width of the grid should be dynamically added based on the json values . IMAGE Link here

I have tried antd cards but each having the same grids . May be flexbox would be ideal I think . Let's say below is the json I receive . The grid for name ="Bill should be large than the next based on the score value

[{"NAME":"Holiday","Score":25}, 
{"NAME":"Bargain","Score":16}, 
{"NAME":"Frequent","Score":5}, 
{"NAME":"Weekend","Score":32}]

Solution

  • You can technically do something in that direction with grid, although your score values seem a bit arbitrary and will therefore not result in a completely filled grid like in your visual. For that you'd have to decide what the column count on each row should be and then somehow "normalize" your scores so they fit into the columns...

    const data = [
      {"name": "Holiday", "score": 25}, 
      {"name": "Bargain", "score": 16}, 
      {"name": "Frequent", "score": 5}, 
      {"name": "Weekend", "score": 32},
    ];
    
    document.querySelector('.grid').innerHTML = data.map(obj => {
      return `<div class="item" style="grid-column-end: span ${obj.score };"><span>${obj.name}</span></div>`;
    }).join('\n');
    .grid {
      background: gold;
      display: grid;
      grid-template-columns: repeat(41, 1fr);
      grid-gap: 8px;
    }
    
    .item {
      align-items: center;
      background: lightcoral;
      color: white;
      display: flex;
      font-size: 12px; font-family: sans-serif;
      height: 100px;
      justify-content: center;
    }
    <div class="grid">
    
    </div>