I use grid with css, I need to make sure element in the center if array number is one or two or three.
<div className={styles.testWrap}>
<div className={styles.testGrid}>
{array.map((value, index) => {
return (
<div className={styles.logoBox} key={index}>
<div
onClick={() => router.push({ pathname: `./brand/${brand.id}` })}
className={styles.logoContainer}
>
<NextImage src={brand.logoUrl} width={180} height={180} alt="pic" />
</div>
</div>
);
})}
</div>
CSS
.testWrap {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
background-color: pink;
.testGrid {
display: grid;
width: 100%;
gap: 24px;
justify-content: center;
margin-bottom: 130px;
@include sm {
width: fit-content;
margin: 0 auto;
grid-template-columns: auto auto;
grid-template-rows: auto auto;
margin-bottom: 197px;
}
@include md {
// grid-template-columns: auto auto auto; if array number is three
// grid-template-columns: auto auto; if array number is two
// grid-template-columns: auto; if array number is one
grid-template-columns: params; // How do I get dynamic params over here ?
justify-content: center;
grid-gap: 55px;
width: 100%;
margin-bottom: 195px;
}
}
}
>Solution :
To dynamically adjust the grid-template-columns property based on the number of items within an array in a React component, you can make efficient use of CSS Custom Properties, often referred to as CSS variables.
The idea is to leverage JavaScript’s string manipulation capabilities within the React component to dynamically generate the desired value for the grid-template-columns property.
Here’s a proposed implementation:
<div
className={styles.testWrap}
style={{
"--dynamic-columns": "auto ".repeat(array.length).trim()
}}
>
<div className={styles.testGrid}>
{/* ...rest of the code */}
</div>
</div>
In this method, we use JavaScript’s string repeat() method to generate the desired "auto" repetitions based on the array length, and then trim the leading space using trim().
.testWrap {
/*... other styles ...*/
.testGrid {
/*... other styles ...*/
@include md {
grid-template-columns: var(--dynamic-columns);
/*... other styles ...*/
}
}
}
This approach is efficient and scalable. The utilization of CSS variables ensures a seamless integration between the dynamic JS environment and the CSS styling, providing an elegant solution to the challenge at hand.