Reputation: 349
I have a cardList and I want to use a different color for every card in the cardList. I tried to do it by my self but it became complicated.
Here is the cardList:
return (
<Container>
<Row className="row gy-4 mt-4">
{profsData && profsData.data.map((item) => (
<Col key={item.id} className='col-3'>
<Card className='h-100 w-100 py-5'>
<Card.Body>
<Card.Title>{item.username}</Card.Title>
<Card.Text>
{item.bio}
</Card.Text>
{item.college && (<h6 className='fw-bold mt-5'>Collège</h6>)}
{item.lycee && (<h6 className='fw-bold mb-5'>Lycée</h6>)}
<Button variant="primary" onClick={() => handleShow(item.id)}>Rendez-Vous</Button>
</Card.Body>
</Card>
</Col>
))}
</Row>
</Container>
)
and here is the array of color with the function selecting randomly a color:
const variant = [
'Primary',
'Secondary',
'Success',
'Danger',
'Warning',
'Info',
'Light',
'Dark',
]
const index = Math.floor(Math.random() * variant.length)
const colorPicked = variant[index]
I'm using a map()
function to display the data in the profsData array and I can't use another map()
for the variant array inside the first map()
function.
Upvotes: 2
Views: 564
Reputation: 202618
If you want a pseudo-random color then compute a random color for each card that is mapped.
return (
<Container>
<Row className="row gy-4 mt-4">
{profsData?.data.map((item) => {
const randIndex = Math.floor(Math.random() * variant.length)
const randomVariant = variant[randIndex];
return (
<Col key={item.id} className='col-3'>
... use randomVariant in JSX ...
</Col>
);
})}
</Row>
</Container>
);
If you just want a different color per card then use the mapped data index and select a variant color. Taking the modulus of the mapped index by variant
array length ensures a valid index within the array.
return (
<Container>
<Row className="row gy-4 mt-4">
{profsData?.data.map((item, index) => {
const selectedVariant = variant[index % variant.length];
return (
<Col key={item.id} className='col-3'>
... use selectedVariant in JSX ...
</Col>
);
})}
</Row>
</Container>
);
Upvotes: 1
Reputation: 356
const variant = [
'Primary',
'Secondary',
'Success',
'Danger',
'Warning',
'Info',
'Light',
'Dark',
]
{profsData && profsData.data.map((item,index) => (
<Col key={item.id} className='col-3'>
<Card variant={variant[index] ? variant[index] : variant[0]} className='h-100 w-100 py-5'>
...
</Card.Body>
</Card>
</Col>
))}
Upvotes: 0