0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

in this case, into className are written the first letters of the word "makeStyles". first div has className "m" secondt div has "a" etc
Ooooh my bad, I will update my answer. I wouldn't use useStyle for this case and do some inline CSS like this : <div key={index} style={{ background: data[index].color }}>
It looks like it works. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.