Home > front end >  change backgroundColor For every item when using map in react.js
change backgroundColor For every item when using map in react.js

Time:10-07

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?

CodePudding user response:

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> )

CodePudding user response:

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>);
  • Related