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

What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. H ...

"Manipulate the contents of a state array by adding or removing items at specific indices in React, alongside other array

I am facing a challenge in removing items from an array that have been added to a state array in React. While I can successfully add new items, the removal process is not working as expected. The current remove function removes all elements, but I only wan ...

Incorporating imports disrupts the script configuration in Nuxtjs 3

Issues arise when utilizing the import statement within the context of <script setup>, causing subsequent code to malfunction. After installing the @heroicons package and importing it as a component in the <template>, all code below the import ...

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

When the canvasJS range column chart is below the horizontal axis, modify the color and width of the bars

For each day of the week, there are records of fuel consumed and refilled. I envisioned representing this data in a range column chart using CanvasJS library. The unique aspect is that the color and width of the bars should change dynamically based on thei ...

Using THREE.js: Object3D Dimension Shrinkage

Is there a way to disable sizeAttenuation for an Object3D in THREE.js? I'm working on rendering a trajectory at a massive scale using arrow helpers to show the motion direction. I want the arrow heads to maintain their orientation without changing si ...

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

Update the next-auth session object once the user has been successfully updated through a patch request

I've scoured the depths of the Internet in search of an answer, but alas, my efforts have been fruitless. I attempted some tricks I found online, but they didn't do the trick for me. So, once a user logs in and a session is created, how can I up ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

Fading text that gradually vanishes depending on the viewport width... with ellipses!

I currently have a two-item unordered list positioned absolutely to the top right of the viewport. <header id="top-bar"> <ul> <li> <a href="#">David Bowie</a> </li> <li> ...

Use Backbone.js to dynamically insert partial views based on specific routes, similar to how ng-view works in AngularJS

After gaining experience with AngularJs, I am now looking to dive into Backbone.js. However, I am struggling to understand how this library handles routes and partial views/templates "injection". In Angular, we can easily set up static components like th ...

Execute a function once all images have finished loading

My current approach involves utilizing a function to load images from an array: for (var i = 0; i < images_list.length; i++) { var img = new Image(); img.onload = function() { images_objects.push(this); ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Update the value after verifying the element

I am trying to retrieve data from my database and update the values when an element is clicked (accepting user posts). The code I have written seems to work, but I encounter an error stating that props.actions is not a function when clicking on an element. ...