What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element

However, when I try to implement it in the code below, the background color ends up being transparent:

{
  modules.map((module, index) => (
    <div className='carousel-module shadow'
      style={{ background: "#" + Math.floor(Math.random()*16777215).toString(16)}}
    >
      <p className='module-element-text'>{module.name ? module.name : "N/A"}</p>
      <p className='module-element-text'>{module.code ? module.code : "N/A"}</p>
      <Button onClick={() => setShow(false)}
          variant="success" className='modules-list-button'>
          Load
      </Button>
    </div>
  ))
}

I would appreciate any suggestions on how to successfully achieve this feature

Answer №1

Here is a simple JavaScript function that I created to generate random hex color codes. Using this method ensures that the color generated does not have an alpha value and remains opaque.

function generateRandomHexColor() {
    let toHexString = function (number) {
        let hexString = number.toString(16);
        while (hexString.length < 2) { hexString = '0' + hexString; }
        return hexString;
    };
    
    let red = toHexString(Math.floor(Math.random() * 256));
    let green = toHexString(Math.floor(Math.random() * 256));
    let blue = toHexString(Math.floor(Math.random() * 256));
    
    return '#' + red + green + blue;
}

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

Mysterious symbols appearing in text/html encoding on Firefox

When I retrieve a text/html content from a ".txt" file using jquery.ajax(), everything works fine in other browsers except for Firefox. In Firefox, I see strange characters like ... This is my code: $.ajax({ url: "menuProcesso.txt", ...

`Creating a union of prop types in TypeScript and React`

I'm facing an issue with a component prop that I need to restrict to specific strings using a union type, as shown below: type HeadingProps = { level?: 'h1' | 'h2' | 'h3' | 'h4'| 'h5' | 'h6&a ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

Implement a JavaScript and jQuery code that alternates between fading in and fading out every two items in a

Can someone help me figure out how to create a loop that fades in and out every 2 items from an unordered list using jQuery? I've been trying to do this, but my loop only processes one item at a time. <div> <ul> <li>item1</li ...

Create an animated underline for two CSS tabs

I'm interested in learning how to create a similar animation using JS, jQuery, or Vue Transitions with Bootstrap. I want to achieve the effect of moving the line under TAB1 to the right when TAB2 is clicked. Can anyone guide me on animating the div sm ...

Display an additional div when hovering over form input

I am currently in the process of designing a search bar animation. Specifically, I want the search history to appear when hovering over the search bar. However, I am facing an issue where the code doesn't seem to work when I use .search-bar-input:hove ...

React encountering difficulty showing images stored on a local path

Just starting out with React and I'm facing an issue while trying to show images from the src/images folder. Even after double-checking the path, the image still doesn't appear on the screen. Take a look at my image tag path and folder structure ...

Parsing JSON in an Express application

I have developed a small application to test a larger one that I am currently working on. The small application reads data from a CSV file and then attempts to send this data to my API endpoint using POST requests. This is necessary as I need to send a lar ...

Sending a JavaScript variable to a Flask url_for function

There is an endpoint that requires a value in the URL and then generates content to be displayed within a specific div. I'm trying to construct the URL using url_for with a JavaScript variable, but it seems that $variable1 is being treated as a string ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair: { "example": [ { "firstName": " ...

Using Vue as the host platform and React as the remote component in a microfrontend setup

I'm in the process of developing a microfrontend application that utilizes Vue for the host and React for the remote component. For this project, I am utilizing Vite along with Module Federation (vite-plugin-federation). Host Application App.vue: & ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

Encountering Excessive Open Files Error with NextJS Deployment

I'm encountering a challenge in my Production environment during peak traffic hours. Any assistance with pinpointing the origin of this issue would be greatly appreciated. Error logs - [Error: EMFILE: too many open files, open '/app/.next/static ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...