1

the problem is I want to add a certain property or actually a few properties, one of which is background color, to every object in the array depending of the other value of the same object in that array. So let's say I have an array of objects like:

let myObj = {
    name: "myObj1",
    value: 12,
    year: 2020
}
/* So the array looks like this: */
let columns = [];
columns.push({name:"myObj1",value:12,year:2020});
columns.push({name:"myObj2",value:3,year:2019});
columns.push({name:"myObj3",value:7,year:2018});

Now i want to add styling like backgroundColor depending on the year if it is odd or even. for example even year should be red color and odd year should be blue color. Let's say i have following code:

class App1 extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <MyCompononent columns={columns} />
            </div>
        )
    }
}

If i add className to div which displays MyComponent, then MyComponent will have this class, and i want to each column have its own class or its own styling. I'm looking for something like property to each column style={backgroundColor: red} or columns={columns.forEach(x => x.year % 2 === 0 ? {className: red} : {className: blue}}

Is this possible?

Greetings, MC

2 Answers 2

2

This is how you can check for even/odd and change color for lists.

export default function App() {
  let columns = [];
  columns.push({ name: "myObj1", value: 12, year: 2020 });
  columns.push({ name: "myObj2", value: 3, year: 2019 });
  columns.push({ name: "myObj3", value: 7, year: 2018 });
  return (
    <div className="App">
      <ul>
        {columns.map(({ year, name }, index) => (
          <li
            key={index}
            style={{ backgroundColor: year % 2 === 0 ? "red" : "blue" }}
            >
            {name}-{year}
          </li>
        ))}
      </ul>
    </div>
  );
}

Working example Live demo

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

1 Comment

it looks good, but you created unordered list... i'm rendering my component...but ahhh idk
0

Did you considered using nth-child css rules?

https://developer.mozilla.org/es/docs/Web/CSS/:nth-child

1 Comment

it will not work. My styling is based on the property of the object in the array. nth-child goes every n thing...

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.