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

Learn how to execute shell commands on a Linux server from a Node.js application by utilizing Socket.io for establishing a connection. This includes tasks such as running "ls -ltr", changing

After successfully establishing a connection with my Linux server, I aim to execute shell commands for automation purposes such as changing directories and creating new folders. The main objective is to connect to the Linux server through a webpage, wher ...

What causes the CSS width property to vary when using the display:inline property?

There is a piece of code that contains a <ul> element with the default css property display:block. Here is the code snippet: ul,li{ list-style-type:none; padding:0; /*display:inline;*/ } #parent{ width:100%; /*height:50px;*/ background-color ...

What could be causing the Or operator to malfunction within the ng-pattern attribute in AngularJS?

Currently, I am implementing the ng-pattern="/^(([A-Za-z]{0,5}) | ([0-9]{0,10}))$/". However, it seems like the input control is not accepting values such as "asd" or "09", despite my expectation that both should be valid inputs. Do you think the pipe sy ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

Searching for data in Node.js using Mongoose and dates

I'm in search of a way to execute a specific query with mongoose. In my mongodb database, I have data structured like this: "startDateTime" : ISODate("2017-03-22T00:00:00.000Z"), "endDateTime" : ISODate("2017-03-27T00:00:00.000Z"), My goal is to r ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

Using Jquery to retrieve data in sections from a server and continuously add it to a file on the client side

I have a large dataset stored in JSON format on a Postgres Server with hundreds of thousands of rows. To prevent memory overload on the server, I need to provide users with the ability to download the data in chunks rather than all at once. This requires a ...

Why is TS1005 triggered for Redux Action Interface with an expectation of '=>'?

I'm finding it difficult to identify what's causing this issue, as shown in the esLint error from Typescript displayed in the screenshot below: https://i.stack.imgur.com/pPZa7.png Below is the complete code, which consists of actions for redux. ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

Executing SQL queries in JavaScript using PHP functions

Is it allowed, or is it a good practice? It worked for me, but what issues might I face in the future? Just to clarify, I am new to PHP scripting. // button <button type="button" class="btn btn-primary" id="Submit-button" >Save changes</button> ...

Getting Started with CSS Alignment - A Novice's Guide

Recently, I embarked on my journey to learn HTML and CSS with the ambition of creating a login page. Although I've successfully crafted a basic version, I'm encountering an issue where the input boxes and labels are misaligned, giving off an unpr ...

JSON-based Material UI Dropdown Selector

I'm having trouble populating a Material UI Drop down with JSON Data. Can someone help me identify the issue? Below is the code snippet that contains the JSON data and the relevant code. const json = { ResponseMetadata: { RequestId: "1B29B45E145594A ...

What is the best way to delete a CSS class from a specific element in a list using React?

I need to implement a functionality in React that removes a specific CSS class from an item when clicking on that item's button, triggering the appearance of a menu. Here is my code snippet. import "./Homepage.css" import React, { useState, ...

The process of loading an image becomes stuck once the submit button is pressed

I have multiple JSP pages where I use an ajax call to submit data. On these pages, I am able to display a loading image before the ajax call and hide it once the call is complete, which works perfectly. $(document).ajaxComplete(function() { $("#loadi ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

How can I implement two dropdowns in jquery?

One of my dropdown menus is currently utilizing this code to fetch the selected value: $(document).on('change','#DropDown1',function() { var value1 = $(this).children("option:selected").val(); var data = {"key": value1}; ...

Showing JSON data in AngularJS

I need help with AngularJS to display JSON output. Is using gridOptions the best approach for this? I'm trying to print labels starting from the root in reverse order - label/parent's label/parent's parent's label/... { artifac ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

How should GET and Data be returned in NextJS 13.4 API? Should we use NextResponse, Response, or NextAPIResponse?

After researching, it seems there are various opinions on the correct way to return a response to an API in NextJS. It appears that some of the confusion may stem from the transition between versions 13.4 and previous ones. However, I will outline my exper ...