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

The modal window pops up immediately upon the first click

Experience a dynamic modal element that springs to life with just the click of a button or an image. The magic lies in the combination of HTML, CSS, and jQuery code: <div id="modal-1" class="modal"> <div class="button modal-button" data-butto ...

Guide to adding a theme switcher feature to your current React website

Currently, I am faced with a challenge involving two theme files, theme.js and theme-dark.js, within the context of a complex React-based website. Despite having already set up the site, I am struggling to find a way to allow users to seamlessly switch bet ...

Utilizing absolute imports in Typescript directory structure

Our team has a preferred structure for organizing React code, which looks like this: components/ button.tsx slider.tsx index.ts helpers/ math.ts auth.ts index.ts constants/ config.ts api.ts index.ts In this setup, each ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

The functionality for navigating the Angular uib-dropdown using the keyboard is currently experiencing issues

I am currently utilizing Angular Bootstrap 2.2.0 in conjunction with Angular 1.5. Despite enabling the keyboard-nav option, I am experiencing issues with keyboard navigation on UIB dropdowns. Below is the snippet of my code: <div class="btn-group" ...

Toggle between a list view and grid view for viewing photos in a gallery with a

Hey there, I'm a newbie on this site and still getting the hang of jQuery and JavaScript. Though I do have a good grasp on HTML and CSS. Currently, I'm working on a photo gallery webpage as part of my school project using the Shadowbox plugin. Wh ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

Where does the browser retrieve the source files for "sourcemapped" JavaScript files from?

As I begin working on an existing project built with angular JS, upon opening chrome dev tools and navigating to the "source" view, a message appears: Source map detected... This prompts me to see a link to: https://i.stack.imgur.com/RZKcq.png The fi ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Having trouble making z-index work on a child div with absolute positioning

I am attempting to design a ribbon with a triangle div positioned below its parent div named Cart. <div class="rectangle"> <ul class="dropdown-menu font_Size_12" role="menu" aria-labelledby="menu1" style="min-width: 100px; z-index: 0"> & ...

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Can you include both a routerLink and a click event on the same anchor tag?

I am facing an issue with my li elements. When a user clicks on them, it should open a more detailed view in another component. However, I noticed that it takes TWO clicks to show the data I want to display. The first click opens the component with an em ...

D3 not distinguishing between bars with identical data even when a key function is implemented

When attempting to create a Bar chart with mouseover and mouseout events on the bars using scaleBand(), I encountered an issue. After reviewing the solution here, which explains how ordinal scale treats repeated values as the same, I added a key to the dat ...

Display only the static placeholder in Angular 2 multi-select feature

My experience with angular 4 is fairly new and I've recently delved into using the angular multiselect feature with the npm package available here. I've managed to successfully configure it, as well as capture selected and deselected items/event ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Updating the state in React following an API call

I've attempted multiple methods to update the state, but it seems that it never actually changes. Below is the JSON data that I am trying to update my state with: export class Provider extends Component { state = { posts: [], profileinfo: { ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...