Rendering n number of grid items based in the dynamic column size

Viewed 186

I have a slider that ranges from 1 and up to 3. The slider's on change event sets the value of a CSS variable (e.g. :root { --colNum: 1 } ) so I am able to dynamically change the number of grid columns.

What I am trying to achieve is (let's say I have six images in total):

  • When I have one column set, I would like to display only the first image, full size and hide the five remaining images.
  • When I have two columns set, I would like to display the first four images, two in each row and hide the two remaining images.
  • When I have three columns set, I would like to display all the six images, three per row.

Similar to the following images:

  • 1 column and 1 image (1 row) 1 column
  • 2 columns and 4 images (2 rows) 2 columns
  • 3 columns and 6 images (2 rows) 3 columns

I have created a sandbox, tried different examples but none of them fit my needs so I have left it in an "initial state".

I am not sure if I am overthinking that but I am open to hear any suggestions or even other approaches in how I could achieve that result.

Thanks in advance.

1 Answers

I have finally achieved what I wanted. Maybe it can help someone else facing similar case as mine. The solution is going to be in the same sandbox and I will be improving that to completely fit my needs.

Solution

In short, as I previously mentioned I have the CSS var (--colNum) changing its value dynamically based in the slider value.

I have filtered the items from the images array to conditionally render or not the images based in the colNum and image index values.

If I have a condition which renders the images I pass down a style props containing the height and width of the images and in cases it should not render I just return null.

Probably not the best approach but still.

const imagesByColumn = images.map((image, index) => {
    // One Image One Column
    if (colNum === '1') {
      if (index === 0) {
        const style = { width: '300px', height: '200px' };
        return <Image key={index} url={image.url} style={style} />;
      } else {
        return null;
      }
    }

    // Two Columns 4 Images
    if (colNum === '2') {
      if (index >= 0 && index < 4) {
        const style = { width: '170px', height: '120px' };
        return <Image key={index} url={image.url} style={style} />;
      } else {
        return null;
      }
    }

    // 3 Columns 6 Images
    if (colNum === '3') {
      const style = { width: '150px', height: '100px' };
      return <Image key={index} url={image.url} style={style} />;
    }

    return null;
  });
Related