What is the best way to allocate a unique color to every item within an array?

I've been working on some JavaScript code that pulls a random color from a selection:

const colors = [blue[800], green[500], orange[500], purple[800], red[800]];
const color = colors[Math.floor(Math.random() * colors.length)];

Within my JSX code, I display an image with a randomly chosen color

{this.state.data.map((n, i) => {
    return (
    <Avatar style={{backgroundColor: color}}>{n.author.charAt(0).toUpperCase()}</Avatar>
    );
})}

The trouble I'm running into is that every item displayed ends up being the same random color, like orange. My goal is to have each item show up in a unique color, but I'm unsure how to make this happen.

Answer №1

let colors = [blue[800], green[500], orange[500], purple[800], red[800]];
let getColor = () => colors[Math.floor(Math.random() * colors.length)];

{this.state.data.map((item, index) => {
   return (
    <Avatar style={{backgroundColor: getColor()}}> 
      {item.author.charAt(0).toUpperCase()}
    </Avatar>
   );
})}

Answer №2

hopefully this is effective

{this.state.data.map((n, i) => {
   // repositioning the following line 
    const shade = shades[Math.floor(Math.random() * shades.length)];
    
    return (
    <Avatar style={{backgroundColor: shade}}>{n.author.charAt(0).toUpperCase()}</Avatar>
    );
})}

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

The integration of lodash debounce with a NextJS function is failing with the error message "[TypeError: search(...) is undefined]

I've been developing a feature in NextJS that allows users to search for YouTube videos based on their input. In order to optimize API calls, I decided to implement lodash debounce with the useCallback hook. However, I'm encountering an issue whe ...

discord.js: Imported array not displaying expected values

I've been facing an issue with accessing elements from an imported array. Even though the array is successfully imported, attempting to access its elements using [0] results in undefined. Here's how I exported the array in standList.js: exports. ...

A promise was caught with the following error: "Error in ./Search class Search - inline template:4:0 caused by: Maximum call stack size exceeded"

As a newcomer to Angular2, I am currently developing a web application that requires three separate calls to a REST API. To test these calls, I decided to simulate the API responses by creating three JSON files with the necessary data. However, my implemen ...

Counting the elements on a page using Selenium and Node.js: A step-by-step guide

I've been experimenting with Selenium in Javascript using NodeJS and I'm trying to tally up some elements based on CSS selectors. So far, I've attempted a few methods: client.findElements(By.css(".some-class")).size(); However, I encounte ...

Explaining the process of how React prevents UI updates in the useLayoutEffect function

Upon inspecting this code in a browser and navigating to the "elements" tab within the developer tools, it becomes evident that clicking the button adds the element to the DOM but doesn't render it. How does React achieve this? What specific browser m ...

Exploring the globe with 3D raycasting, orbit controls, and dynamic camera rotation

It would be great if users could hover over the small spheres in different countries to get more information. Initially, I thought using a raycaster would help achieve this, but it's not responding to mouse movements as expected. It seems like the is ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

For my Bootstrap website, it's a constant struggle to balance between having a responsive menu item and ensuring its correct visual appearance

I need help with creating a unique menu design for my website. On the desktop site, I want to display "username/password/sign in" buttons, while on the mobile responsive version I only want to show a single "sign in" option that redirects users to the sign ...

What is the best way to incorporate Vue Apollo into a Vue Vite project?

I'm currently working on integrating Vue Apollo into a Vite project using the composition API. Here is how my main.js file looks: import { createApp } from 'vue' import App from './App.vue' import * as apolloProvider from '../ ...

Ways to invoke a function within a React Material-UI component

Currently, I am in the process of setting up a chat system that allows users to add emojis. To achieve this feature, I have devised a function that produces a component containing both text and an image. Here is the function I have implemented: test: fu ...

Two columns with one column having a fixed width

I am looking to create a layout with two columns, one for content and the other for a sidebox. The sidebox should have a fixed width while the content column can shrink as needed. Eventually, both columns will stack to 100% width, but I want the content c ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

Facing Quick Refresh Problems: The NextJs is currently experiencing issues when used with a local package. Is there a way to manually clear the cache to ensure smooth development

I have developed an application using NextJs along with React and mobx-state-tree (although it could also be context or redux) as the package manager. I have structured all the stores in an npm package named SMK (state management kit) that I created to ena ...

Demonstration of Concurrent Page Processing in Flask

Currently, I am working on an application that heavily utilizes graphics using libraries such as Raphael and graphdracula. The main functionality of the application involves drawing various graphs across different pages named graph1, graph2, and graph3. L ...

Is it possible to use a lowercase variable name in ReactJS for a class name?

Just starting out with ReactJS and I noticed that when I declare a class like var quiz=React.createClass{}.. it doesn't work unless I change the variable to Quiz. Is this a requirement or am I overlooking something? I'm currently using JSX and ...

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Error: The addDoc() function in FireBase was encountered with invalid data, as it included an unsupported field value of undefined during the execution

As I attempt to input data into the firebase database, an error arises: 'FireBaseError: Function addDoc() called with invalid data. Unsupported field value: undefined'. The registration form requests 2 inputs - name and email. The function handle ...

Avoiding the duplication of selected items in a dropdown within a gridview can be achieved effectively by implementing a JavaScript/jQuery

In my gridview, which contains multiple rows, each row has a dropdown (select in HTML). My goal is to prevent the user from selecting the same item from the dropdown list for different rows. For instance, if a user selects "New York": Assigning rooms: U ...

Unable to delete data in Laravel 8

I am new to Laravel and facing an issue when trying to delete a row with a modal. The problem is that only the first row is getting removed and I can't figure out the reason. Here is my modal setup: <p class="card-text"><small clas ...