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

An issue occurred with the session being undefined in Node.js Express4

I'm encountering an issue where my session is undefined in new layers even after setting the value within an "if" statement. /*******************************************/ /**/ var express = require('express'), /**/ cookieParse ...

Activate all chosen CSS circles

I'm currently working on creating a progress bar using CSS circles. The idea is that when you click on each circle in sequence (1, 2, 3), all three circles and the line connecting them will fill up with red color. If you then go back (3, 2, 1), the co ...

An iteration in Javascript/NodeJS using the forEach loop

I am working with a forEach Loop in my code: <% users.forEach(function(user) { %> <tr> <td><%= user.studio %></td> <td><%= user.name %></td> <td><%= user.email %></td> ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Adjust element based on the position of another element (sticky)

Is it possible to rotate a text block so that it remains anchored to the bottom of a red rectangle, even when the rectangle is rotated? Similar to how it works in Figma, but simpler. For example, if I rotate the rectangle by 180 degrees, the text should be ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Determine whether an object exists within another object and merge its value into the formatted object

When filling out a form, I have a formattedData object that holds a deep copy of the original data object. If a field in the form is changed, I must update the formatted data object with properties from the values object. To simulate this scenario, I crea ...

Internet Explorer is failing to render SVG as content within a pseudo element such as :before or :after

Looking to tackle an issue that stems from the following discussion: Is there a way to use SVG as content in a pseudo element :before or :after. I'm attempting to add a svg triangle after a div using a pseudo-class. div{ background-color: black; w ...

Changing the name of the static folder in React when building the application

Is there a method to change the name of the "static" directory while running "npm run build"? ...

The type 'string' does not share any properties with the type 'CSSProperties'

How can I resolve the issue of Type 'string' has no properties in common with type 'CSSProperties'? const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = ...

React sending incorrect date to Node.js

Observing the date in Node through console logging shows the accurate date: console.log(`Date according to Node: ${new Date()}`); Date according to Node: Mon Apr 04 2022 17:52:20 GMT+0200 However, when I transmit the date from React via a POST request ...

Associate the URL with the object to retrieve the corresponding object

When iterating through this array, I currently loop through it in the following manner: {props.choosenMovie.characters.map((characters) => ( <p>{characters}</p> /* This displays the URL of course */ ))} The URLs contain a name object th ...

Determining the best CSS based on the user's preferred color scheme using media queries

Is it possible to separate my CSS into two files, one for dark mode and one for light mode, and conditionally load them using only HTML without the need for JavaScript? I haven't been able to find any examples on https://developer.mozilla.org. Could ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

Guide to adding an icon within an HTML `<input>` element

Is anyone able to help me successfully place my icon font inside the search input field? I've tried adjusting the margin and padding, but nothing seems to be working! If you have any insights or suggestions, please let me know. Your help is greatly a ...

Despite using twitter bootstrap, the elements on my webpage are still overlapping one another

While implementing Twitter Bootstrap on my website, I encountered a problem where elements start overlapping if the window size is reduced. This issue does not look appealing, and I expected Twitter Bootstrap to ensure that my website is fully responsive a ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Tips for creating a vertical Angular Material slider with CSS

Attempting to modify the angular material directive to render vertically has been a challenge. I experimented with using transform:rotate in the CSS, however, it resulted in the slider behaving and rendering differently. md-slider { position: absolute ...

Delaying navigation to the next URL until a distinct category name is identified

Within this section of JSP code, I am implementing JavaScript and AJAX to validate the uniqueness of a category name. When the submit button is pressed for the first time, it prompts the user to enter a category name. Subsequently, an AJAX call is made to ...