Nageeb Darwish
Nageeb Darwish

Reputation: 311

change backgroundColor For every item when using map in react.js

I get objects from api , i get it and mapping over it and return <p></p> like this:

data.map((item) => <p> {item.p} </p> )

my question is: how can i give every paragraph a diffrent backgrounColor from each other?

Upvotes: 0

Views: 1017

Answers (2)

Haim Abeles
Haim Abeles

Reputation: 1021

You can make different colors for each element in the following way

data.map((item) => <p style={{ backgroundColor: `#${((Math.random() * 0xfffff * 1000000).toString(16)(.slice(0,6)}` }}> {item.p} </p> )

Upvotes: 2

Sudhanshu Kumar
Sudhanshu Kumar

Reputation: 2044

You can have a colour variable associated with each item

data.map((item) => <p style={{backgroundColor: item.color}}>{item.p}</p>);

or you can do it randomly

data.map((item, index) => <p style={{backgroundColor: `#43f${index}FC`}}>{item.p}</p>);

Upvotes: 0

Related Questions