What is the best way to assign a unique background color to each individual card in my card list?

I have a list of cards and I want to assign a unique color to each card in the list. I attempted to do this on my own, but it ended up being more complex than I anticipated.

Here is the list of cards:

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>
)

Additionally, here is an array of colors with a random selection function:

const variant = [
  'Primary',
  'Secondary',
  'Success',
  'Danger',
  'Warning',
  'Info',
  'Light',
  'Dark',
]

const index = Math.floor(Math.random() * variant.length)
const colorPicked = variant[index]

The challenge arises because I am utilizing a map() function to display data from the profsData array and incorporating another map() for the color variant array within the initial function isn't feasible.

Answer №1

To achieve a pseudo-random color scheme, assign a random color to each card that is being 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'>
            ... incorporate randomVariant into JSX ...
          </Col>
        );
      })}
    </Row>
  </Container>
);

If you simply want each card to have a different color, use the index of the mapped data along with a selected variant color. By using the modulus operator with the length of the variant array, a valid index within the array is ensured.

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'>
            ... utilize selectedVariant in JSX ...
          </Col>
        );
      })}
    </Row>
  </Container>
);

Answer №2

const styles = [
    'Primary',
    'Secondary',
    'Success',
    'Danger',
    'Warning',
    'Info',
    'Light',
    'Dark',
  ]    
{dataSet && dataSet.info.map((element,i) => (
          <Col key={element.id} className='col-3'>
            <Card style={styles[i] ? styles[i] : styles[0]} className='h-100 w-100 py-5'>
              ...
              </Card.Body>
            </Card>
          </Col>
        ))}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object. The API requires the data to be structured like this: "data": [ { "id": 1, "nombre": "AGUASBLANCAS-AGB&qu ...

Error: The function prevDeps.join is not defined in Next.js

I need assistance in creating a search bar using next js and firebase. The functionality involves extracting the slug from the URL and processing it through my search algorithm. However, I encountered an issue where if the user utilizes the search bar mult ...

Creating a text box that displays an inverted input

Hello, I'm looking to create a text box where if I input 1 then 2, it will display 21. Then if I enter 3, it should show 321. I am currently using Vue.js on my front end. Here is what I have attempted so far: I experimented with methods such as watc ...

``Is there a specific scenario where the use of getInitialProps is recommended when automatically redirecting from one

Within my application, I have set up an auto-redirect from the root directory '/' to '/PageOne' with the following code: const Home = () => { const router = useRouter(); useEffect(() => { router.push('/pageone', ...

React input with outlined phone number design

Hey there! I'm new to learning React, so this question might be easy for some, but any help is greatly appreciated. Right now, I'm working on a project using Material UI and I need to create an outlined phone number input with a flag and label th ...

Tips on disregarding events within an html table

I have a see-through table with a width set to 100% that houses various HTML content. I am utilizing the table to properly center a particular element on the screen. However, the table is intercepting mouse events and preventing users from clicking on lin ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

"Implementing responsive design with Material-UI components in React using

It has become quite annoying to constantly see all these warnings related to DOMNesting. No matter what I do, I can't seem to get rid of them completely. Here is a typical example: Warning: validateDOMNesting(...): <table> cannot appear as a des ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

What is the reason behind TypeScript failing to provide type safety in a generic higher order component which introduces extra properties into React components?

I'm currently working on developing a versatile higher order component, but have encountered an issue with type safety not being enforced. Interestingly, when attempting the same implementation without using generics, the type safety is verified as ex ...

PHP query will execute even in the absence of clicking the button

I'm encountering an unusual issue. I've defined a query to insert two names into the database, and I've used Javascript(Jquery) to ensure it only runs when the create button is clicked. However, the script seems to be executing every time I ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

JS client-side form validation involves communicating with the server to verify user input

I currently have an HTML form that is being validated on the client side. Below is a snippet of the code: <form id='myForm' onsubmit='return myFormValidation()'> ... </form> Now, I want to incorporate server-side valida ...

What is causing Mocha.js to be unable to locate the module?

Having trouble with mocha.js not being able to locate my path! Here's the directory structure I have set up for my node course project: ///////Root --package.json --node_modules/ --playground --server -server.js -db -models ...

What is the optimal platform for sending OTP via SMS in Nodejs? I experimented with twilio, but my account kept getting suspended because of my Geo location

Before, I used Twilio for another project without any issues. However, after creating 2 new accounts with my business email and adding $20 to send SMS, my account was immediately suspended for verification. Now, when I try to log in, I am only seeing the f ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...

Having trouble with my jQuery .hover() code not running as expected

Whenever I hover over my divs, I want them to change color. However, the code doesn't seem to be working as expected when I try to do so. I suspect that the issue might be related to the z-index property used in the class that I am trying to hover ove ...

My React higher order component implementation is revealing the protected route momentarily

import { useRouter } from "next/router"; import { useEffect } from "react"; import axios from "axios"; export default (ChildComponent) => { const enhanceComponent = (props) => { const router = useRouter(); co ...