This question mainly pertains to CSS, and there are numerous ways to accomplish the desired outcome.
I suggest utilizing display: grid
and grid-template-columns
for creating grid-based layouts:
.grid {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 2px;
}
.grid img {
width: 100%;
}
<div class="grid">
<img src="https://picsum.photos/200/200" />
<img src="https://picsum.photos/200/200" />
<img src="https://picsum.photos/200/200" />
<img src="https://picsum.photos/200/200" />
<img src="https://picsum.photos/200/200" />
</div>
If you wish to create placeholder cells, you can simply add some CSS to hide them:
.grid {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 2px;
}
.grid img {
width: 100%;
}
.grid img[src=""] {
display: none;
}
<div class="grid">
<img src="https://picsum.photos/200/200" />
<img src="https://picsum.photos/200/200" />
<img src="" />
<img src="" />
</div>
Update
To enhance your code, consider this approach - if the name
field is empty, provide a visual hint for easier styling:
const GridItem = ({ name, path, altText }) => {
return (
<li className={'grid-item'} key={name}>
<a className={`${name ? 'link' : 'link link__empty'}`}>
<div className={'image'}>
<img src={path} alt={altText} />
</div>
<div className={'image-text'}>{name}</div>
</a>
</li>
);
Alternatively, leave the cell empty:
const GridItem = ({ name, path, altText }) => {
return (
<li className={'grid-item'} key={name}>
<a className={'link'}>
(name &&
<React.Fragment>
<div className={'image'}>
<img src={path} alt={altText} />
</div>
<div className={'image-text'}>{name}</div>
</React.Fragment>)
</a>
</li>
);
The rendering will look similar to this:
* {
box-sizing: border-box;
}
.grid {
display: flex;
flex-wrap: wrap;
list-style: none;
}
.grid-item {
/* Exclude border to create a 4-column grid */
flex: 0 1 calc(25% - 2px);
/* Adjust for 1px border */
border: solid #000 1px;
}
.link {
text-decoration: none;
}
.image {
width: 100%;
}
.image-text {
text-align: center;
}
.link__empty *{
/* Hide all children in case of emptiness */
display: none;
}
<ul class="grid">
<li class="grid-item">
<a class="link" href="#">
<img class="image" src="example.jpg" alt="Example Image" />
<div class="image-text">Example Text</div>
</a>
</li>
<li class="grid-item">
<a class="link" href="#">
<img class="image" src="example.jpg" alt="Example Image" />
<div class="image-text">Example Text</div>
</a>
</li>
<li class="grid-item">
<a class="link link__empty" href="#">
<img class="image" src="" alt="" />
<div class="image-text"></div>
</a>
</li>
</ul>