Miltosh
Miltosh

Reputation: 91

How to style from an array of objects with using material-ui

I'm use functional component of reactjs. I have an array of objects in which the styles are specified

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

I need to render as many elements on the page as there are objects in the data array, and each element gets its own unique color (the first element gets color from the first object, the second from the second, etc.).

For this I use the custom hook useStyles from material-ui.

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

I expand the HTML part itself like this

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

In this case, I have 2 identical div elements, with the same property

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

CodeSandBox Example

Where did I go wrong?

Upvotes: 0

Views: 1090

Answers (1)

Chandelier Axel
Chandelier Axel

Reputation: 237

It's because .map always return an array, doing so divColor property is equal to :

['#000', '#fff']

What I would do is this :

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

Doing so, the first mark will get the first color in the array, and so on

Upvotes: 1

Related Questions