Learn how to efficiently apply styles to multiple objects within an array using the material-ui library

Currently, I'm utilizing the functional component of React.js. Within this component, I have an array of objects that contain specific styles.

const data = [
        {
            id: 1,
            color: '#000'
        },
        {
            id: 2,
            color: '#fff'
        }
        // and so on
    ]

The objective is to display a number of elements on the page equal to the number of objects in the data array, where each element has a unique color assigned (e.g., first element gets color from first object, second from second, etc.).

To achieve this, I am using the custom hook useStyles from Material-UI.

const useStyles = makeStyles((theme) => ({
    divColor: {
        background: data.map((el) => (
            el.color
        )
        )
    }
}));

This setup translates into the HTML structure as follows:

{data.map((el, index) => <div key={index} className={classes.divColor} />)}

However, the issue arises where I end up with two identical div elements, both having the same property applied:

.makeStyles-startAccident-4 {
    background: #000, #fff;
}

Trying to troubleshoot this problem? Check out the CodeSandBox Example for more insights.

What could be causing this error?

Answer №1

The reason behind this is that .map always returns an array, which means the divColor property will be set to:

['#000', '#fff']

One way to approach this would be:

{marksId.map((el, index) => <div key={index} style={{ background: data[index].color }}>)}

This way, each mark will correspond to a color in the array sequentially.

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

After loading ajax content onto the page, the scroll bars fail to appear

I am currently constructing a website that loads page content through ajax. Everything seems to be functioning perfectly, except for a peculiar issue I have encountered in Chrome and Safari. Surprisingly, it is working flawlessly in IE! The problem lies i ...

Using ${} syntax to implement dynamic logic when constructing a string in Express.js

I need to iterate through an object and display values for each one while creating a string. Any suggestions on how to achieve something like this: const body = ` <h1>Values</h1> ${ for (value in values) { return `<h2>Ind ...

Experiencing difficulties when integrating the pdf-viewer-reactjs module within Next.js framework

I recently integrated the pdf-viewer-reactjs library into my Next.js project and encountered the following error: error - ./node_modules/pdfjs-dist/build/pdf.js 2094:26 Module parse failed: Unexpected token (2094:26) You may need an appropriate loader to h ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

I have managed to update the Immutable and Primitive Data-Types in JS. Now, the question arises - are these truly Primitives or are the concepts in

In JavaScript, there are 4 primitive data types that store values directly: String, Number, Boolean, and Symbol. I am excluding undefined and null from this list as they are special data types with unique characteristics. One key feature of primitives is ...

Exploring the Issue of Switch State Not Persisting in DropdownMenu in Jetpack Compose

Seeking assistance with creating a to-do app for Android incorporating Material 3 & Jetpack Compose. Need help in implementing a drop-down menu feature that enables users to filter tasks based on their specific "Category" preference using Switch. Here is a ...

Adjust the width to be consistent across all columns in the Material UI Data Grid

Is there a way to distribute the width of columns equally based on the container width? Feel free to explore this demo here In the demo, when width is removed, a default width of 100px is applied. Can we apply percentages in width or distribute the width ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

Sorry, but you can only use one 'in' filter in your query

this.ref.collection("users", ref => ref.where("uid1","in", [reciverId, senderId]) .where("uid2","in", [reciverId, senderId])) throws an error stating: "Invalid query. Multiple 'in' filters cannot be used." ...

CSS selector for GTM trigger that is not specific to any particular element

I am attempting to develop a CSS selector that can target the specific entries within the page-top-menu: Header menu - Menu 1 DE #page-top-menu > div > div.menu-wrapper > ul > li.i39.dropdown.layer.item-type-1.catid-0eca5a6c6e53f281b9e0469ca3d ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

"Integrate envMap into the materials section of the model.json file

I successfully exported an object from Blender to .json format for use with three.js. I manually added all the maps to the exported file, which were not included by the exporter but could easily be manually added after mapping correctly in Blender. model. ...

How can I show information on the same page as a link by simply clicking on it?

My goal is to create a functionality where clicking on a link will display specific information. Currently, all the links and their corresponding information are displayed at once. I want to change this so that the links are displayed first, and the inform ...

The functionality of Express JS routers is experiencing issues

As I delved into learning nodejs and express, I decided to create a basic router. Initially, everything seemed to be working fine, but upon reopening the project, I encountered an issue. var express = require('express'); var app = express(); var ...

What is the best way to apply a box-shadow to a specific side of an element?

How can I apply a box shadow to only the right side of a block element? Currently, I achieve this by wrapping the inner element with a box-shadow in an outer element with padding-right and overflow:hidden to hide the other three sides of the shadow. Is the ...

Is it possible to add a bottom border without having slanted corners?

I am looking to design a box with different colors - red on the left, right, and top, and grey at the bottom. However, I want the bottom border of the box to be flat. HTML <div class="ts"></div> CSS .ts { height:100px; width:100 ...

Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj <div id="progressBar"> <div class=& ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Deactivate checkbox based on dropdown selection

I'm facing an issue where I need to disable a checkbox when a certain option is selected from a dropdown inside a datatable in my xhtml file. The dropdown has options like L, C, UV, and more, and when "L" is chosen, the checkbox should be disabled. B ...

What is the best way to execute multiple functions in sequence and halt the process if any of them encounter an error?

I am working with multiple Javascript functions that manipulate the DOM and run ajax requests. My goal is to execute these functions sequentially, one after the other, and only proceed if none of them return false from their ajax request. If any function r ...